Last active
November 1, 2018 05:23
-
-
Save wellingtonjhn/c18b2922b886b75ba6326e2c2a52b756 to your computer and use it in GitHub Desktop.
Built-in UseExceptionHandler extension method
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 ExceptionHandlerExtensions | |
| { | |
| public static void UseGlobalExceptionHandler(this IApplicationBuilder app, ILoggerFactory loggerFactory) | |
| { | |
| app.UseExceptionHandler(builder => | |
| { | |
| builder.Run(async context => | |
| { | |
| var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>(); | |
| if (exceptionHandlerFeature != null) | |
| { | |
| var logger = loggerFactory.CreateLogger("GlobalExceptionHandler"); | |
| logger.LogError($"Unexpected error: {exceptionHandlerFeature.Error}"); | |
| context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; | |
| context.Response.ContentType = "application/json"; | |
| var json = new | |
| { | |
| context.Response.StatusCode, | |
| Message = "An error occurred whilst processing your request", | |
| Detailed = exceptionHandlerFeature.Error | |
| }; | |
| await context.Response.WriteAsync(JsonConvert.SerializeObject(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, IHostingEnvironment env, ILoggerFactory loggerFactory) | |
| { | |
| // ... código omitido | |
| app.UseGlobalExceptionHandler(loggerFactory); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment