| | 1 | | using Despesas.GlobalException.CustomExceptions.Core; |
| | 2 | | using Microsoft.AspNetCore.Http; |
| | 3 | | using Microsoft.Extensions.Logging; |
| | 4 | | using System.Net; |
| | 5 | | using System.Text.Json; |
| | 6 | |
|
| | 7 | | namespace Despesas.GlobalException; |
| | 8 | |
|
| | 9 | | public class GlobalExceptionMiddleware |
| | 10 | | { |
| | 11 | | private readonly RequestDelegate _next; |
| | 12 | | private readonly ILogger<GlobalExceptionMiddleware> _logger; |
| | 13 | |
|
| 0 | 14 | | public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger) |
| 0 | 15 | | { |
| 0 | 16 | | _next = next; |
| 0 | 17 | | _logger = logger; |
| 0 | 18 | | } |
| | 19 | |
|
| | 20 | | public async Task InvokeAsync(HttpContext context) |
| 0 | 21 | | { |
| | 22 | | try |
| 0 | 23 | | { |
| 0 | 24 | | await _next(context); |
| 0 | 25 | | } |
| 0 | 26 | | catch (CustomException ex) |
| 0 | 27 | | { |
| 0 | 28 | | await HandleExceptionAsync(context, ex.StatusCode, ex.Message); |
| 0 | 29 | | } |
| 0 | 30 | | catch (ArgumentException ex) |
| 0 | 31 | | { |
| 0 | 32 | | await HandleExceptionAsync(context, (int)HttpStatusCode.BadRequest, ex.Message); |
| 0 | 33 | | } |
| 0 | 34 | | catch (Exception ex) |
| 0 | 35 | | { |
| | 36 | | // Verifica se é uma exceção do EF Core / repositório |
| 0 | 37 | | if (!await EfCoreExceptionHandler.HandleAsync(context, ex, _logger)) |
| 0 | 38 | | { |
| | 39 | | /* Vide Docker && Kurbenetes Qualquer outra exceção inesperada é invocada _logger.LogError(...) dentro d |
| | 40 | | /e vai para o Console e Debug Output (sem configuração extra... appsettings.json). |
| | 41 | | */ |
| 0 | 42 | | _logger.LogError(ex, "Erro inesperado"); |
| 0 | 43 | | await HandleExceptionAsync(context, StatusCodes.Status500InternalServerError, |
| 0 | 44 | | "Ocorreu um erro inesperado. Tente novamente mais tarde."); |
| 0 | 45 | | } |
| 0 | 46 | | } |
| 0 | 47 | | } |
| | 48 | |
|
| | 49 | | private static async Task HandleExceptionAsync(HttpContext context, int statusCode, string message) |
| 0 | 50 | | { |
| 0 | 51 | | context.Response.ContentType = "application/json"; |
| 0 | 52 | | context.Response.StatusCode = statusCode; |
| | 53 | |
|
| 0 | 54 | | var response = new |
| 0 | 55 | | { |
| 0 | 56 | | success = false, |
| 0 | 57 | | error = message |
| 0 | 58 | | }; |
| | 59 | |
|
| 0 | 60 | | await context.Response.WriteAsync(JsonSerializer.Serialize(response)); |
| 0 | 61 | | } |
| | 62 | | } |