Spaces:
Runtime error
Runtime error
Download src/SCM.Api/Middleware/ErrorHandlingMiddleware.cs from rafaeldavila/scm-api: direct link, hf CLI and curl.
- Browser
- Download file 3.07 kB
-
https://huggingface.co/spaces/rafaeldavila/scm-api/resolve/main/src/SCM.Api/Middleware/ErrorHandlingMiddleware.cs
- Command line
-
hf download hf://spaces/rafaeldavila/scm-api/src/SCM.Api/Middleware/ErrorHandlingMiddleware.cs
-
curl -L -o ErrorHandlingMiddleware.cs https://huggingface.co/spaces/rafaeldavila/scm-api/resolve/main/src/SCM.Api/Middleware/ErrorHandlingMiddleware.cs
3.07 kB
| using System.Data.Common; | |
| using System.Net; | |
| using System.Text.Json; | |
| using FluentValidation; | |
| using SCM.Shared.Api; | |
| using SCM.Shared.Exceptions; | |
| namespace SCM.Api.Middleware; | |
| /// <summary> | |
| /// Middleware global de tratamento de erros. Converte exceções conhecidas em respostas | |
| /// no formato padrão { success, message, errors[] } e nunca expõe stack traces. | |
| /// </summary> | |
| public sealed class ErrorHandlingMiddleware | |
| { | |
| private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); | |
| private readonly RequestDelegate _next; | |
| private readonly ILogger<ErrorHandlingMiddleware> _logger; | |
| public ErrorHandlingMiddleware(RequestDelegate next, ILogger<ErrorHandlingMiddleware> logger) | |
| { | |
| _next = next; | |
| _logger = logger; | |
| } | |
| public async Task InvokeAsync(HttpContext context) | |
| { | |
| try | |
| { | |
| await _next(context); | |
| } | |
| catch (Exception ex) | |
| { | |
| await HandleAsync(context, ex); | |
| } | |
| } | |
| private async Task HandleAsync(HttpContext context, Exception exception) | |
| { | |
| var (status, message, errors) = exception switch | |
| { | |
| ValidationException ve => ( | |
| HttpStatusCode.BadRequest, | |
| "Erro de validação.", | |
| ve.Errors.Select(e => e.ErrorMessage).Distinct().ToList()), | |
| DomainException de => (HttpStatusCode.BadRequest, de.Message, (List<string>?)null), | |
| NotFoundException nfe => (HttpStatusCode.NotFound, nfe.Message, null), | |
| ConflictException ce => (HttpStatusCode.Conflict, ce.Message, null), | |
| UnauthorizedAccessException ue => (HttpStatusCode.Unauthorized, ue.Message, null), | |
| // Violações de integridade do Postgres (Dapper lança DbException) viram 409 amigável | |
| // em vez de 500 genérico — ex.: tentar excluir um registro ainda referenciado. | |
| DbException { SqlState: "23503" } => ( | |
| HttpStatusCode.Conflict, | |
| "Não é possível excluir: existem registros vinculados a este item.", | |
| (List<string>?)null), | |
| DbException { SqlState: "23505" } => ( | |
| HttpStatusCode.Conflict, | |
| "Já existe um registro com esses dados (valor duplicado).", | |
| (List<string>?)null), | |
| _ => (HttpStatusCode.InternalServerError, "Ocorreu um erro inesperado.", null) | |
| }; | |
| if (status == HttpStatusCode.InternalServerError) | |
| _logger.LogError(exception, "Erro não tratado ao processar {Method} {Path}", | |
| context.Request.Method, context.Request.Path); | |
| else | |
| _logger.LogWarning("Requisição rejeitada ({Status}): {Message}", (int)status, message); | |
| context.Response.Clear(); | |
| context.Response.StatusCode = (int)status; | |
| context.Response.ContentType = "application/json"; | |
| var payload = ApiResponse.Fail(message, errors); | |
| await context.Response.WriteAsync(JsonSerializer.Serialize(payload, JsonOptions)); | |
| } | |
| } | |