@@ -21,10 +21,15 @@ internal record CapturedException(
2121
2222public class JsonExceptionMiddleware
2323{
24+ private readonly ILogger < JsonExceptionMiddleware > _logger ;
2425 private readonly RequestDelegate _next ;
2526
26- public JsonExceptionMiddleware ( RequestDelegate next )
27+ public JsonExceptionMiddleware (
28+ ILogger < JsonExceptionMiddleware > logger ,
29+ RequestDelegate next
30+ )
2731 {
32+ _logger = logger ;
2833 _next = next ;
2934 }
3035
@@ -36,25 +41,27 @@ public async Task InvokeAsync(HttpContext httpContext)
3641 }
3742 catch ( Exception ex )
3843 {
39- await HandleExceptionAsync ( httpContext , ex ) ;
44+ await HandleExceptionAsync ( _logger , httpContext , ex ) ;
4045 }
4146 }
4247
43- public static async Task < T > InvokeWithExceptionHandler < T > ( HttpContext httpContext , Func < Task < T > > action )
48+ public static async Task < T > InvokeWithExceptionHandler < T > ( ILogger logger , HttpContext httpContext , Func < Task < T > > action )
4449 {
4550 try
4651 {
4752 return await action ( ) ;
4853 }
4954 catch ( Exception ex )
5055 {
51- await HandleExceptionAsync ( httpContext , ex ) ;
56+ await HandleExceptionAsync ( logger , httpContext , ex ) ;
5257 throw ;
5358 }
5459 }
5560
56- private static async Task HandleExceptionAsync ( HttpContext httpContext , Exception ex )
61+ private static async Task HandleExceptionAsync ( ILogger logger , HttpContext httpContext , Exception ex )
5762 {
63+ logger . LogError ( ex , "An unhandled exception occurred." ) ;
64+
5865 HttpStatusCode GetStatusCode ( )
5966 {
6067 if ( ex . Data . Contains ( "HttpStatusCode" ) && ex . Data [ "HttpStatusCode" ] is HttpStatusCode statusCode )
@@ -83,4 +90,4 @@ public static class JsonExceptionMiddlewareExtensions
8390{
8491 public static IApplicationBuilder UseJsonExceptionHandler ( this IApplicationBuilder builder ) =>
8592 builder . UseMiddleware < JsonExceptionMiddleware > ( ) ;
86- }
93+ }
0 commit comments