Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.25 KB | None | 0 0
  1. namespace Squire.Core.Middlewares
  2. {
  3.     public class GlobalErrorHandlerMiddleware
  4.     {
  5.         private readonly RequestDelegate _next;
  6.         private readonly ILogger _logger;
  7.         private readonly bool _showException;
  8.  
  9.         public GlobalErrorHandlerMiddleware(RequestDelegate next, ILogger logger, bool showException = false)
  10.         {
  11.             _next = next;
  12.             _logger = logger;
  13.             _showException = showException;
  14.         }
  15.  
  16.         public async Task Invoke(HttpContext context)
  17.         {
  18.             try
  19.             {
  20.                 await _next(context);
  21.             }
  22.             catch (Exception ex)
  23.             {
  24.                 _logger.Error(ex, "Unhandled exception");
  25.                 context.Response.StatusCode = StatusCodes.Status500InternalServerError;
  26.  
  27.                 if (_showException)
  28.                     await context.Response.WriteAsync(ex.ToString());
  29.             }
  30.         }
  31.     }
  32.  
  33.     public static class GlobalErrorHandlerMiddlewareExtensions
  34.     {
  35.         public static IApplicationBuilder UseGlobalErrorHandler(this IApplicationBuilder builder, bool showException = false)
  36.         {
  37.             return builder.UseMiddleware<GlobalErrorHandlerMiddleware>(showException);
  38.         }
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement