46 lines
1.6 KiB
C#
46 lines
1.6 KiB
C#
using System.Text.Json;
|
|
using mws.backend.dotnet.application.Common;
|
|
|
|
namespace mws.backend.dotnet.api.Middleware;
|
|
|
|
public class ApiExceptionMiddleware(RequestDelegate next, ILogger<ApiExceptionMiddleware> logger)
|
|
{
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await next(context);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await HandleAsync(context, ex);
|
|
}
|
|
}
|
|
|
|
private async Task HandleAsync(HttpContext context, Exception ex)
|
|
{
|
|
var (statusCode, message) = ex switch
|
|
{
|
|
BadRequestException => (StatusCodes.Status400BadRequest, ex.Message),
|
|
UnauthorizedException => (StatusCodes.Status401Unauthorized, ex.Message),
|
|
ForbiddenException => (StatusCodes.Status403Forbidden, ex.Message),
|
|
NotFoundException => (StatusCodes.Status404NotFound, ex.Message),
|
|
_ => (StatusCodes.Status500InternalServerError, "An unexpected error occurred"),
|
|
};
|
|
|
|
if (statusCode == StatusCodes.Status500InternalServerError)
|
|
{
|
|
logger.LogError(ex, "Unhandled exception in {Path}", context.Request.Path);
|
|
}
|
|
|
|
context.Response.StatusCode = statusCode;
|
|
context.Response.ContentType = "application/json";
|
|
await context.Response.WriteAsync(JsonSerializer.Serialize(new { message }));
|
|
}
|
|
}
|
|
|
|
public static class ApiExceptionMiddlewareExtensions
|
|
{
|
|
public static IApplicationBuilder UseApiExceptionMiddleware(this IApplicationBuilder app)
|
|
=> app.UseMiddleware<ApiExceptionMiddleware>();
|
|
} |