using System.Text.Json;
using FozFc.Api.Application.Common;
namespace FozFc.Api.Api.Middleware;
///
/// Converts into structured JSON error responses and
/// turns any unhandled exception into a 500 (logged, without leaking details).
///
public sealed class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (ApiException ex)
{
await WriteError(context, ex.StatusCode, ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception processing {Method} {Path}", context.Request.Method, context.Request.Path);
await WriteError(context, 500, "Internal server error.");
}
}
private static Task WriteError(HttpContext context, int status, string message)
{
if (context.Response.HasStarted) return Task.CompletedTask;
context.Response.Clear();
context.Response.StatusCode = status;
context.Response.ContentType = "application/json";
return context.Response.WriteAsync(JsonSerializer.Serialize(new { error = message }));
}
}