Advertisement
Guest User

Untitled

a guest
May 3rd, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.99 KB | None | 0 0
  1. // in startup
  2. app.UseMiddleware(typeof(ErrorHandlingMiddleware));
  3.  
  4. public class ErrorHandlingMiddleware
  5.     {
  6.         private readonly RequestDelegate next;
  7.  
  8.         public ErrorHandlingMiddleware(RequestDelegate next)
  9.         {
  10.             this.next = next;
  11.  
  12.         }
  13.  
  14.         public async Task Invoke(HttpContext context)
  15.         {
  16.             try
  17.             {
  18.                 await next(context);
  19.             }
  20.             catch (Exception ex)
  21.             {
  22.                 await HandleExceptionAsync(context, ex);
  23.             }
  24.         }
  25.  
  26.         private async Task HandleExceptionAsync(HttpContext context, Exception exception)
  27.         {
  28.             var code = HttpStatusCode.InternalServerError;
  29.  
  30.             var result = JsonConvert.SerializeObject(new { error = exception.Message });
  31.             context.Response.ContentType = "application/json";
  32.             context.Response.StatusCode = (int)code;
  33.             await context.Response.WriteAsync(result);
  34.  
  35.         }
  36.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement