Advertisement
oldhowl

Untitled

Jan 24th, 2020
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1.  public class ExceptionToJsonMiddleware
  2.     {
  3.         private readonly RequestDelegate _next;
  4.         private ILogger<ExceptionToJsonMiddleware> _logger;
  5.  
  6.         public ExceptionToJsonMiddleware(RequestDelegate next)
  7.         {
  8.             this._next = next;
  9.         }
  10.  
  11.         public async Task Invoke(HttpContext context, ILoggerFactory loggerFactory)
  12.         {
  13.             try
  14.             {
  15.                 await _next(context);
  16.             }
  17.             catch (Exception ex)
  18.             {
  19.                 _logger = loggerFactory.CreateLogger<ExceptionToJsonMiddleware>();
  20.                
  21.                 _logger.LogError(JsonConvert.SerializeObject(new ExceptionProfilerModel
  22.                 {
  23.                     Path = context.Request.Path.HasValue ? context.Request.Path.Value : string.Empty,
  24.                     Request = request,
  25.                     ExceptionMessage = ex.Message,
  26.                     StackTrace = ex.StackTrace,
  27.                     RequestTime = DateTimeOffset.Now
  28.                 }, Formatting.Indented));
  29.  
  30.  
  31.                 await HandleExceptionAsync(context, ex);
  32.             }
  33.         }
  34.  
  35.        
  36.  
  37.         private Task HandleExceptionAsync(HttpContext context, Exception exception)
  38.         {
  39.             var code = HttpStatusCode.InternalServerError; // 500 if unexpected
  40.             switch (exception)
  41.             {
  42.                 case FriendlyException ex:
  43.                     code = HttpStatusCode.BadRequest;
  44.                     break;
  45.                 case AccessDeniedException ex:
  46.                     code = HttpStatusCode.Forbidden;
  47.                     break;
  48.                 case EntityNotFoundException ex:
  49.                     code = HttpStatusCode.NotFound;
  50.                     break;
  51.             }
  52.  
  53.  
  54.             var result = JsonConvert.SerializeObject(new {error = exception.Message});
  55.             context.Response.ContentType = "application/json";
  56.             context.Response.StatusCode = (int) code;
  57.             return context.Response.WriteAsync(result);
  58.         }
  59.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement