The ASP.NET Core solution (mws.api/mws.application/mws.domain/ mws.infrastructure) existed only as untracked working files. Adding it to version control, plus a .gitignore for build output and local tooling directories, so the CQRS/mediator refactor plan has a real git history to branch and diff against.
46 lines
1.5 KiB
C#
46 lines
1.5 KiB
C#
using System.Text.Json;
|
|
using Mws.Application.Common;
|
|
|
|
namespace Mws.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>();
|
|
} |