All checks were successful
Mindforge API Build and Deploy / Build Mindforge API Image (push) Successful in 1m8s
Mindforge Cronjob Build and Deploy / Build Mindforge Cronjob Image (push) Successful in 1m19s
Mindforge API Build and Deploy / Deploy Mindforge API (internal) (push) Successful in 11s
Mindforge Cronjob Build and Deploy / Deploy Mindforge Cronjob (internal) (push) Successful in 10s
Mindforge Web Build and Deploy (internal) / Build Mindforge Web Image (push) Successful in 2m25s
Mindforge Web Build and Deploy (internal) / Deploy Mindforge Web (internal) (push) Successful in 12s
48 lines
1.5 KiB
C#
48 lines
1.5 KiB
C#
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<ExceptionHandlingMiddleware> _logger;
|
|
|
|
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> 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);
|
|
}
|
|
}
|
|
}
|