using EntrustSettle.Model; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Net; using System.Threading.Tasks; namespace EntrustSettle.Extensions.Middlewares { public class ExceptionHandlerMiddleware { private readonly RequestDelegate _next; public ExceptionHandlerMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { if (ex == null) return; var message = ex.Message; switch (ex) { case UnauthorizedAccessException: context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; break; default: context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; break; } context.Response.ContentType = "application/json"; await context.Response .WriteAsync(JsonConvert.SerializeObject(new ApiResponse(StatusCode.CODE500, message).MessageModel)) .ConfigureAwait(false); } } } }