using System.Net;
using System.Text.Json;
using GermanApp.Shared.Models;
namespace GermanApp.Shared.Middleware;
///
/// Global exception handling middleware.
/// Catches exceptions and returns consistent error responses.
///
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public ExceptionMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception occurred: {Message}", ex.Message);
await HandleExceptionAsync(httpContext, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var response = new ApiErrorResponse(
"An unexpected error occurred. Please try again later.",
context.Response.StatusCode,
exception.Message
);
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
return context.Response.WriteAsync(JsonSerializer.Serialize(response, options));
}
}
///
/// Extension method to add exception middleware.
///
public static class ExceptionMiddlewareExtensions
{
public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder builder) =>
builder.UseMiddleware();
}