Last active
November 5, 2022 15:24
-
-
Save wellingtonjhn/fe1d2791b8aa358e11f6a785388b7777 to your computer and use it in GitHub Desktop.
Problem Details Exception Handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static class ProblemDetailsExtensions | |
| { | |
| public static void UseProblemDetailsExceptionHandler(this IApplicationBuilder app, ILoggerFactory loggerFactory) | |
| { | |
| app.UseExceptionHandler(builder => | |
| { | |
| builder.Run(async context => | |
| { | |
| var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>(); | |
| if (exceptionHandlerFeature != null) | |
| { | |
| var exception = exceptionHandlerFeature.Error; | |
| var problemDetails = new ProblemDetails | |
| { | |
| Instance = context.Request.HttpContext.Request.Path | |
| }; | |
| if (exception is BadHttpRequestException badHttpRequestException) | |
| { | |
| problemDetails.Title = "The request is invalid"; | |
| problemDetails.Status = StatusCodes.Status400BadRequest; | |
| problemDetails.Detail = badHttpRequestException.Message; | |
| } | |
| else | |
| { | |
| var logger = loggerFactory.CreateLogger("GlobalExceptionHandler"); | |
| logger.LogError($"Unexpected error: {exceptionHandlerFeature.Error}"); | |
| problemDetails.Title = exception.Message; | |
| problemDetails.Status = StatusCodes.Status500InternalServerError; | |
| problemDetails.Detail = exception.Demystify().ToString(); | |
| } | |
| context.Response.StatusCode = problemDetails.Status.Value; | |
| context.Response.ContentType = "application/problem+json"; | |
| var json = JsonConvert.SerializeObject(problemDetails, SerializerSettings.JsonSerializerSettings); | |
| await context.Response.WriteAsync(json); | |
| } | |
| }); | |
| }); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Startup | |
| { | |
| public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) | |
| { | |
| // ... código omitido | |
| app.UseProblemDetailsExceptionHandler(loggerFactory); | |
| app.UseMvc(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment