Skip to content

Instantly share code, notes, and snippets.

@skalahonza
Created April 22, 2019 09:06
Show Gist options
  • Select an option

  • Save skalahonza/0df56b0708b9a9efe23dadff6164f406 to your computer and use it in GitHub Desktop.

Select an option

Save skalahonza/0df56b0708b9a9efe23dadff6164f406 to your computer and use it in GitHub Desktop.
Middle for caching exceptions on .net core web API.
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