- Add Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore package - Add Serilog.AspNetCore and Serilog.Sinks.Console packages - Configure Serilog with bootstrap logger and configuration - Add Health Checks endpoint at /health with DbContext check - Configure CORS with AllowAll policy for development - Create ApiResponse, ApiErrorResponse, and PaginatedResponse models - Create ExceptionMiddleware for global error handling - Restructure Program.cs with try-catch-finally for proper logging Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
62 lines
1.8 KiB
C#
62 lines
1.8 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
using GermanApp.Shared.Models;
|
|
|
|
namespace GermanApp.Shared.Middleware;
|
|
|
|
/// <summary>
|
|
/// Global exception handling middleware.
|
|
/// Catches exceptions and returns consistent error responses.
|
|
/// </summary>
|
|
public class ExceptionMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly ILogger<ExceptionMiddleware> _logger;
|
|
|
|
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> 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));
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Extension method to add exception middleware.
|
|
/// </summary>
|
|
public static class ExceptionMiddlewareExtensions
|
|
{
|
|
public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder builder) =>
|
|
builder.UseMiddleware<ExceptionMiddleware>();
|
|
}
|