Files
UniVerse/backend/UniVerse.Api/Middleware/ExceptionHandlingMiddleware.cs
T
serega404 935e4ed37a
Backend CI / build-and-test (push) Failing after 11m26s
🚀 Create and publish a Docker image / Detect changes in backend and frontend (push) Failing after 14m2s
Frontend CI / build-and-check (push) Failing after 19m55s
🚀 Create and publish a Docker image / Build & publish frontend image (push) Failing after 14m7s
🚀 Create and publish a Docker image / Build & publish backend image (push) Failing after 14m59s
🚀 Create and publish a Docker image / Update stack on Portainer (push) Failing after 15m0s
feat: добавил изменение промта для админа
2026-05-21 21:58:33 +03:00

56 lines
2.0 KiB
C#

using System.Net;
using System.Text.Json;
using UniVerse.Domain.Exceptions;
namespace UniVerse.Api.Middleware;
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 (Exception ex) { await HandleExceptionAsync(context, ex); }
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var (statusCode, title) = exception switch
{
BadRequestException => ((int)HttpStatusCode.BadRequest, "Bad Request"),
NotFoundException => ((int)HttpStatusCode.NotFound, "Not Found"),
ForbiddenException => ((int)HttpStatusCode.Forbidden, "Forbidden"),
ConflictException => ((int)HttpStatusCode.Conflict, "Conflict"),
UnauthorizedAccessException => ((int)HttpStatusCode.Unauthorized, "Unauthorized"),
_ => ((int)HttpStatusCode.InternalServerError, "Internal Server Error")
};
if (statusCode == 500)
_logger.LogError(exception, "Unhandled exception");
else
_logger.LogWarning("Handled exception: {Message}", exception.Message);
context.Response.ContentType = "application/problem+json";
context.Response.StatusCode = statusCode;
var problem = new
{
type = $"https://httpstatuses.com/{statusCode}",
title,
status = statusCode,
detail = exception.Message,
traceId = context.TraceIdentifier
};
await context.Response.WriteAsync(JsonSerializer.Serialize(problem,
new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }));
}
}