Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ExceptionToJsonMiddleware
- {
- private readonly RequestDelegate _next;
- private ILogger<ExceptionToJsonMiddleware> _logger;
- public ExceptionToJsonMiddleware(RequestDelegate next)
- {
- this._next = next;
- }
- public async Task Invoke(HttpContext context, ILoggerFactory loggerFactory)
- {
- try
- {
- await _next(context);
- }
- catch (Exception ex)
- {
- _logger = loggerFactory.CreateLogger<ExceptionToJsonMiddleware>();
- _logger.LogError(JsonConvert.SerializeObject(new ExceptionProfilerModel
- {
- Path = context.Request.Path.HasValue ? context.Request.Path.Value : string.Empty,
- Request = request,
- ExceptionMessage = ex.Message,
- StackTrace = ex.StackTrace,
- RequestTime = DateTimeOffset.Now
- }, Formatting.Indented));
- await HandleExceptionAsync(context, ex);
- }
- }
- private Task HandleExceptionAsync(HttpContext context, Exception exception)
- {
- var code = HttpStatusCode.InternalServerError; // 500 if unexpected
- switch (exception)
- {
- case FriendlyException ex:
- code = HttpStatusCode.BadRequest;
- break;
- case AccessDeniedException ex:
- code = HttpStatusCode.Forbidden;
- break;
- case EntityNotFoundException ex:
- code = HttpStatusCode.NotFound;
- break;
- }
- var result = JsonConvert.SerializeObject(new {error = exception.Message});
- context.Response.ContentType = "application/json";
- context.Response.StatusCode = (int) code;
- return context.Response.WriteAsync(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement