diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f965d43da..4387e0eec6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased + +### Fixes + +- ASP.NET Core: fix handled not being set for Handled exceptions ([#1111](https://github.com/getsentry/sentry-dotnet/pull/1111)) + ## 3.7.0 ### Features diff --git a/src/Sentry.AspNetCore/SentryMiddleware.cs b/src/Sentry.AspNetCore/SentryMiddleware.cs index 270bd346ab..c2fd8aad87 100644 --- a/src/Sentry.AspNetCore/SentryMiddleware.cs +++ b/src/Sentry.AspNetCore/SentryMiddleware.cs @@ -115,18 +115,21 @@ public async Task InvokeAsync(HttpContext context) var exceptionFeature = context.Features.Get(); if (exceptionFeature?.Error != null) { - CaptureException(exceptionFeature.Error); + CaptureException(exceptionFeature.Error, "IExceptionHandlerFeature"); } } catch (Exception e) { - CaptureException(e); + CaptureException(e, "SentryMiddleware.UnhandledException"); ExceptionDispatchInfo.Capture(e).Throw(); } - void CaptureException(Exception e) + void CaptureException(Exception e, string mechanism) { + e.Data[Mechanism.HandledKey] = false; + e.Data[Mechanism.MechanismKey] = mechanism; + var evt = new SentryEvent(e); _logger.LogTrace("Sending event '{SentryEvent}' to Sentry.", evt); diff --git a/test/Sentry.AspNetCore.Tests/SentryMiddlewareTests.cs b/test/Sentry.AspNetCore.Tests/SentryMiddlewareTests.cs index f593142451..621842a3e7 100644 --- a/test/Sentry.AspNetCore.Tests/SentryMiddlewareTests.cs +++ b/test/Sentry.AspNetCore.Tests/SentryMiddlewareTests.cs @@ -88,6 +88,23 @@ public async Task InvokeAsync_ExceptionThrown_SameRethrown() Assert.Same(expected, actual); } + [Fact] + public async Task InvokeAsync_ExceptionThrown_HandledSetFalse() + { + var expected = new Exception("test"); + _fixture.RequestDelegate = _ => throw expected; + + _fixture.Hub.When(h => h.CaptureEvent(Arg.Any())) + .Do(c => Assert.False((bool)c.Arg().Exception.Data[Mechanism.HandledKey])); + + var sut = _fixture.GetSut(); + + var actual = await Assert.ThrowsAsync( + async () => await sut.InvokeAsync(_fixture.HttpContext)); + + Assert.Same(expected, actual); + } + [Fact] public async Task InvokeAsync_FeatureFoundWithNoError_DoesNotCapturesEvent() { @@ -102,6 +119,21 @@ public async Task InvokeAsync_FeatureFoundWithNoError_DoesNotCapturesEvent() _ = _fixture.Hub.DidNotReceive().CaptureEvent(Arg.Any()); } + [Fact] + public async Task InvokeAsync_FeatureFoundWithError_CapturesEvent() + { + var exception = new Exception(); + var feature = Substitute.For(); + _ = feature.Error.Returns(exception); + _ = _fixture.HttpContext.Features.Get().Returns(feature); + var sut = _fixture.GetSut(); + + await sut.InvokeAsync(_fixture.HttpContext); + + _ = _fixture.Hub.Received().CaptureEvent(Arg.Any()); + Assert.Equal("IExceptionHandlerFeature", exception.Data[Mechanism.MechanismKey]); + } + [Fact] public async Task InvokeAsync_ScopePushed_BeforeConfiguringScope() {