Skip to content

Instantly share code, notes, and snippets.

@abarrenechea
Created May 17, 2022 22:13
Error Handler Middleware
using ApplicationCore.Exceptions;
using System.Net;
using System.Text.Json;
namespace WebApi
{
public class ErrorHandlerMiddleware : IMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await _next(context);
}
catch (Exception error)
{
var response = context.Response;
response.ContentType = "application/json";
switch (error)
{
case CurrencyNotSupportedException:
case CurrencyExchangeNotFoundException:
case ArgumentOutOfRangeException:
response.StatusCode = (int)HttpStatusCode.BadRequest;
break;
case CurrencyNotFoundException:
response.StatusCode = (int)HttpStatusCode.NotFound;
break;
default:
// unhandled error
response.StatusCode = (int)HttpStatusCode.InternalServerError;
break;
}
var result = JsonSerializer.Serialize(new { message = error?.Message });
await response.WriteAsync(result);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment