ref: project structure
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
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>();
|
||||
}
|
||||
Reference in New Issue
Block a user