using System; using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Mindforge.API.Exceptions; namespace Mindforge.API.Middlewares { public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (UserException ex) { _logger.LogWarning(ex, "User error"); await HandleExceptionAsync(context, StatusCodes.Status400BadRequest, ex.Message); } catch (Exception ex) { _logger.LogError(ex, "Internal server error"); await HandleExceptionAsync(context, StatusCodes.Status500InternalServerError, $"Internal server error: {ex.Message}"); } } private static Task HandleExceptionAsync(HttpContext context, int statusCode, string message) { context.Response.ContentType = "application/json"; context.Response.StatusCode = statusCode; var result = JsonSerializer.Serialize(new { error = message }); return context.Response.WriteAsync(result); } } }