/
HiddenLogic
/
Motion-ERP
Обзор
Документация
Войти
/
HiddenLogic
/
Motion-ERP
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
Motion-ERP.API/Middleware/ExceptionHandlingMiddleware.cs
58 строк
2 KB
adnet
Initial commit: Motion-ERP solution structure
30 июл 2026, 17:01
30 июл 2026, 17:01
bf32c92
Код
Авторство
О чём код?
using System.Net; using System.Text.Json; using Motion_ERP_Domain.Exceptions; namespace Motion_ERP_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 Task HandleExceptionAsync(HttpContext context, Exception exception) { _logger.LogError(exception, "Unhandled exception: {Message}", exception.Message); var response = context.Response; response.ContentType = "application/json"; var errorResponse = new { error = exception switch { DomainException de => de.Message, ArgumentException ae => ae.Message, _ => "Внутренняя ошибка сервера." }, statusCode = exception switch { DomainException { } de when de is AssetNotFoundException or ContractNotFoundException or ContractorNotFoundException or TariffNotFoundException => (int)HttpStatusCode.NotFound, DomainException => (int)HttpStatusCode.BadRequest, ArgumentException => (int)HttpStatusCode.BadRequest, _ => (int)HttpStatusCode.InternalServerError } }; response.StatusCode = errorResponse.statusCode; var json = JsonSerializer.Serialize(errorResponse, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); return response.WriteAsync(json); } }