Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // in startup
- app.UseMiddleware(typeof(ErrorHandlingMiddleware));
- public class ErrorHandlingMiddleware
- {
- private readonly RequestDelegate next;
- public ErrorHandlingMiddleware(RequestDelegate next)
- {
- this.next = next;
- }
- public async Task Invoke(HttpContext context)
- {
- try
- {
- await next(context);
- }
- catch (Exception ex)
- {
- await HandleExceptionAsync(context, ex);
- }
- }
- private async Task HandleExceptionAsync(HttpContext context, Exception exception)
- {
- var code = HttpStatusCode.InternalServerError;
- var result = JsonConvert.SerializeObject(new { error = exception.Message });
- context.Response.ContentType = "application/json";
- context.Response.StatusCode = (int)code;
- await context.Response.WriteAsync(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement