add ExceptionHandlingMiddleware

This commit is contained in:
2023-06-12 13:45:54 +02:00
parent 73bfcccc9c
commit 88ccaea826
2 changed files with 43 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
using AB.Domain.Exceptions;
using System.Text.Json;
namespace AB_API.Middleware
{
public class ExceptionHandlingMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext httpContext, Exception ex)
{
httpContext.Response.ContentType = "application/json";
httpContext.Response.StatusCode = ex switch
{
NotFoundException => StatusCodes.Status404NotFound,
_ => StatusCodes.Status400BadRequest
};
var response = new
{
error = ex.Message
};
await httpContext.Response.WriteAsJsonAsync(response);
}
}
}