CODEX_ADK/BACKEND/Codex.Api/Middleware/GlobalExceptionHandler.cs
Svrnty 229a0698a3 Initial commit: CODEX_ADK monorepo
Multi-agent AI laboratory with ASP.NET Core 8.0 backend and Flutter frontend.
Implements CQRS architecture, OpenAPI contract-first API design.

BACKEND: Agent management, conversations, executions with PostgreSQL + Ollama
FRONTEND: Cross-platform UI with strict typing and Result-based error handling

Co-Authored-By: Jean-Philippe Brule <jp@svrnty.io>
2025-10-26 23:12:32 -04:00

62 lines
1.7 KiB
C#

using System.Net;
using System.Text.Json;
namespace Codex.Api.Middleware;
/// <summary>
/// Global exception handler middleware that catches all unhandled exceptions
/// and returns a standardized error response format
/// </summary>
public class GlobalExceptionHandler
{
private readonly RequestDelegate _next;
private readonly ILogger<GlobalExceptionHandler> _logger;
private readonly IWebHostEnvironment _env;
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
public GlobalExceptionHandler(
RequestDelegate next,
ILogger<GlobalExceptionHandler> logger,
IWebHostEnvironment env)
{
_next = next;
_logger = logger;
_env = env;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception occurred: {Message}", ex.Message);
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var response = new
{
message = "An unexpected error occurred",
statusCode = context.Response.StatusCode,
traceId = context.TraceIdentifier,
details = _env.IsDevelopment() ? exception.Message : null
};
var json = JsonSerializer.Serialize(response, JsonOptions);
await context.Response.WriteAsync(json);
}
}