Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ASP.Net Core LastEventID #1573

Merged
merged 3 commits into from
Apr 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
- GetFromRuntimeInformation() in try-catch ([#1554](https://github.com/getsentry/sentry-dotnet/pull/1554))
- Make `Contexts` properties more thread-safe ([#1571](https://github.com/getsentry/sentry-dotnet/pull/1571))
- Fix `PlatformNotSupportedException` exception on `net6.0-maccatalyst` targets ([#1567](https://github.com/getsentry/sentry-dotnet/pull/1567))
- In ASP.Net Core, make sure that `SentrySdk.LastEventId` is accessible from exception handler pages ([#1573](https://github.com/getsentry/sentry-dotnet/pull/1573))

## 3.15.0

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,16 @@ public IActionResult Contact(

var id = sentry.CaptureException(e);

ViewData["Message"] = "An exception was caught and sent to Sentry! Event id: " + id;
ViewData["Message"] = "An exception was caught and sent to Sentry! Event ID: " + id;
}
return View();
}

public IActionResult Test()
{
throw new Exception("Test exception thrown in controller!");
}

public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
"ASPNETCORE_ENVIRONMENT": "Production"
},
"applicationUrl": "http://localhost:5001"
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<h3>Sentry Event ID: @SentrySdk.LastEventId</h3>


<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
Expand Down
10 changes: 10 additions & 0 deletions samples/Sentry.Samples.AspNetCore.Mvc/Views/Home/Test.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
@using Samples.AspNetCore.Mvc
@{
ViewData["Title"] = "Test";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<p>Use this area to provide additional information.</p>


31 changes: 21 additions & 10 deletions samples/Sentry.Samples.AspNetCore.Mvc/Views/Shared/Error.cshtml
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
@model Samples.AspNetCore.Mvc.Models.ErrorViewModel
@using Sentry
@using Sentry.AspNetCore
@inject Microsoft.Extensions.Options.IOptions<SentryAspNetCoreOptions> SentryOptions

@model Samples.AspNetCore.Mvc.Models.ErrorViewModel
@{
ViewData["Title"] = "Error";
}
Expand All @@ -9,14 +13,21 @@
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
<strong>Request ID:</strong> <code>@Model.RequestId</code><br/>
<strong>Sentry Event ID: <code>@SentrySdk.LastEventId</code></strong>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>Development environment should not be enabled in deployed applications</strong>, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>, and restarting the application.
</p>
@if (SentrySdk.LastEventId != SentryId.Empty)
{
<script
src="https://browser.sentry-cdn.com/6.19.4/bundle.min.js"
integrity="sha384-l+UQ7KbPIcq6l4DoWCwMvaOJ0pdJ+oTVGD6GyROFzSriOH1F1f6dl90fOgcigkMX"
crossorigin="anonymous"></script>
<script>
Sentry.init({ dsn: "@(SentryOptions.Value.Dsn)" });
Sentry.showReportDialog({
eventId: "@SentrySdk.LastEventId",
subtitle2: "Event ID: @SentrySdk.LastEventId"
});
</script>
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
</environment>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
Expand All @@ -33,6 +33,7 @@
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="About">About (Razor view throws)</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact (Explicit capture)</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Test">Test (Controller action throws)</a></li>
</ul>
</div>
</div>
Expand All @@ -41,7 +42,7 @@
@RenderBody()
<hr />
<footer>
<p>&copy; 2018 - Sentry.Samples.AspNetCore.Mvc</p>
<p>&copy; @DateTime.Now.Year - Sentry.Samples.AspNetCore.Mvc</p>
</footer>
</div>

Expand Down
14 changes: 10 additions & 4 deletions src/Sentry.AspNetCore/SentryMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,12 @@ public async Task InvokeAsync(HttpContext context)
};
});

// Pre-create the Sentry Event ID and save it on the scope it so it's available throughout the pipeline,
// even if there's no event actually being sent to Sentry. This allows for things like a custom exception
// handler page to access the event ID, enabling user feedback, etc.
var eventId = SentryId.Create();
hub.ConfigureScope(scope => scope.LastEventId = eventId);

try
{
await _next(context).ConfigureAwait(false);
Expand All @@ -111,7 +117,7 @@ public async Task InvokeAsync(HttpContext context)
var exceptionFeature = context.Features.Get<IExceptionHandlerFeature?>();
if (exceptionFeature?.Error != null)
{
CaptureException(exceptionFeature.Error, "IExceptionHandlerFeature");
CaptureException(exceptionFeature.Error, eventId, "IExceptionHandlerFeature");
}
if (_options.FlushBeforeRequestCompleted)
{
Expand All @@ -120,7 +126,7 @@ public async Task InvokeAsync(HttpContext context)
}
catch (Exception e)
{
CaptureException(e, "SentryMiddleware.UnhandledException");
CaptureException(e, eventId, "SentryMiddleware.UnhandledException");
if (_options.FlushBeforeRequestCompleted)
{
await FlushBeforeCompleted().ConfigureAwait(false);
Expand All @@ -136,12 +142,12 @@ async Task FlushBeforeCompleted()
await hub.FlushAsync(timeout: _options.FlushTimeout).ConfigureAwait(false);
}

void CaptureException(Exception e, string mechanism)
void CaptureException(Exception e, SentryId eventId, string mechanism)
{
e.Data[Mechanism.HandledKey] = false;
e.Data[Mechanism.MechanismKey] = mechanism;

var evt = new SentryEvent(e);
var evt = new SentryEvent(e, eventId: eventId);

_logger.LogTrace("Sending event '{SentryEvent}' to Sentry.", evt);

Expand Down
31 changes: 31 additions & 0 deletions test/Sentry.AspNetCore.Tests/SentryMiddlewareTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -607,4 +607,35 @@ public async Task InvokeAsync_SameMiddleWareWithDifferentHubs_CopyOptionsToAllHu
firstHub.Received(1).ConfigureScope(Arg.Is(expectedAction));
secondHub.Received(1).ConfigureScope(Arg.Is(expectedAction));
}

[Fact]
public async Task InvokeAsync_AlwaysSetsLastEventIdOnScope()
{
var sut = _fixture.GetSut();

await sut.InvokeAsync(_fixture.HttpContext);

Assert.NotEqual(SentryId.Empty, _fixture.Scope.LastEventId);
}

[Fact]
public async Task InvokeAsync_SetsEventIdOnEvent()
{
var expected = new Exception("test");
_fixture.RequestDelegate = _ => throw expected;

var sut = _fixture.GetSut();

try
{
await sut.InvokeAsync(_fixture.HttpContext);
}
catch
{
// swallow exception for this test
}

var eventId = _fixture.Scope.LastEventId;
_ = _fixture.Hub.Received().CaptureEvent(Arg.Is<SentryEvent>(e => e.EventId.Equals(eventId)));
}
}