Last active
November 1, 2018 05:24
-
-
Save wellingtonjhn/39f5391a5dcf0cf3e7087765b9a806c1 to your computer and use it in GitHub Desktop.
Custom Global Exception Handler MIddleware
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 GlobalExceptionHandlerMiddleware : IMiddleware | |
| { | |
| private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger; | |
| public GlobalExceptionHandlerMiddleware(ILogger<GlobalExceptionHandlerMiddleware> logger) | |
| { | |
| _logger = logger; | |
| } | |
| public async Task InvokeAsync(HttpContext context, RequestDelegate next) | |
| { | |
| try | |
| { | |
| await next(context); | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.LogError($"Unexpected error: {ex}"); | |
| await HandleExceptionAsync(context, ex); | |
| } | |
| } | |
| private static Task HandleExceptionAsync(HttpContext context, Exception exception) | |
| { | |
| context.Response.ContentType = "application/json"; | |
| context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; | |
| var json = new | |
| { | |
| context.Response.StatusCode, | |
| Message = "An error occurred whilst processing your request", | |
| Detailed = exception | |
| }; | |
| return 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 static class GlobalExceptionHandlerMiddlewareExtensions | |
| { | |
| public static IServiceCollection AddGlobalExceptionHandlerMiddleware(this IServiceCollection services) | |
| { | |
| return services.AddTransient<GlobalExceptionHandlerMiddleware>(); | |
| } | |
| public static void UseGlobalExceptionHandlerMiddleware(this IApplicationBuilder app) | |
| { | |
| app.UseMiddleware<GlobalExceptionHandlerMiddleware>(); | |
| } | |
| } |
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 ConfigureServices(IServiceCollection services) | |
| { | |
| // ... código omitido | |
| services.AddGlobalExceptionHandlerMiddleware(); | |
| } | |
| public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) | |
| { | |
| // ... código omitido | |
| app.UseGlobalExceptionHandlerMiddleware(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment