Created
April 22, 2019 09:06
-
-
Save skalahonza/0df56b0708b9a9efe23dadff6164f406 to your computer and use it in GitHub Desktop.
Middle for caching exceptions on .net core web API.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class ErrorHandlingMiddleware | |
| { | |
| private readonly RequestDelegate _next; | |
| public ErrorHandlingMiddleware(RequestDelegate next) | |
| { | |
| _next = next; | |
| } | |
| public async Task Invoke(HttpContext context) | |
| { | |
| try | |
| { | |
| await _next(context); | |
| } | |
| catch (Exception ex) when(!(ex is ValidationException)) | |
| { | |
| await HandleExceptionAsync(context, ex); | |
| } | |
| } | |
| private static Task HandleExceptionAsync(HttpContext context, Exception exception) | |
| { | |
| HttpStatusCode code; | |
| switch (exception) | |
| { | |
| case UnauthorizedAccessException _: | |
| case SecurityTokenException _: | |
| code = HttpStatusCode.Unauthorized; | |
| break; | |
| case NotFoundException _: | |
| case KeyNotFoundException _: | |
| code = HttpStatusCode.NotFound; | |
| break; | |
| default: | |
| code = HttpStatusCode.InternalServerError; | |
| break; | |
| } | |
| var result = JsonConvert.SerializeObject(new | |
| { | |
| error = exception.Message, | |
| name = exception.GetType().Name | |
| }); | |
| context.Response.ContentType = "application/json"; | |
| context.Response.StatusCode = (int)code; | |
| return context.Response.WriteAsync(result); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment