$mermaidjs
Clean Architecture Demo
Loading...
Searching...
No Matches
ExceptionHandlingMiddleware.cs
Go to the documentation of this file.
1// TaskManagement.API/Middleware/ExceptionHandlingMiddleware.cs
2using Microsoft.AspNetCore.Mvc;
5
7
63public sealed class ExceptionHandlingMiddleware
64{
65 private static readonly Action<ILogger, string, Exception?> LogRequestFailure =
66 LoggerMessage.Define<string>(
67 LogLevel.Error,
68 new EventId(1000, nameof(ExceptionHandlingMiddleware)),
69 "Request failed: {Message}");
70
71 private readonly RequestDelegate _next;
72
73 private readonly ILogger<ExceptionHandlingMiddleware> _logger;
74
76 RequestDelegate next,
77 ILogger<ExceptionHandlingMiddleware> logger)
78 {
79 _next = next;
80 _logger = logger;
81 }
82
83 public async Task InvokeAsync(HttpContext context)
84 {
85 ArgumentNullException.ThrowIfNull(context);
86
87 try
88 {
89 await _next(context).ConfigureAwait(false);
90 }
91#pragma warning disable CA1031
92 catch (Exception ex)
93#pragma warning restore CA1031
94 {
95 LogRequestFailure(_logger, ex.Message, ex);
96 await HandleExceptionAsync(context, ex).ConfigureAwait(false);
97 }
98 }
99
100 private static Task HandleExceptionAsync(HttpContext context, Exception exception)
101 {
102 context.Response.ContentType = "application/json";
103 var (statusCode, problemDetails) = exception switch
104 {
105 ValidationException ve => (
106 StatusCodes.Status400BadRequest,
107 (ProblemDetails)new ValidationProblemDetails(ve.Errors)
108 {
109 Title = "Validation failed",
110 Status = StatusCodes.Status400BadRequest
111 }),
112 NotFoundException ne => (
113 StatusCodes.Status404NotFound,
114 new ProblemDetails
115 {
116 Title = "Resource not found",
117 Detail = ne.Message,
118 Status = StatusCodes.Status404NotFound
119 }),
120 DomainException de => (
121 StatusCodes.Status422UnprocessableEntity,
122 new ProblemDetails
123 {
124 Title = "Business rule violation",
125 Detail = de.Message,
126 Status = StatusCodes.Status422UnprocessableEntity
127 }),
128 _ => (
129 StatusCodes.Status500InternalServerError,
130 new ProblemDetails
131 {
132 Title = "An unexpected error occurred",
133 Status = StatusCodes.Status500InternalServerError,
134 Detail = "Please try again later or contact support."
135 })
136 };
137 context.Response.StatusCode = statusCode;
138 return context.Response.WriteAsJsonAsync(problemDetails);
139 }
140}
ExceptionHandlingMiddleware es middleware de ASP.NET Core para manejo centralizado de excepciones.
ExceptionHandlingMiddleware(RequestDelegate next, ILogger< ExceptionHandlingMiddleware > logger)
NotFoundException se lanza cuando una entidad solicitada no puede ser encontrada.
ValidationException se lanza cuando la validación de entrada falla en la capa de aplicación.
DomainException es la clase de excepción base para todos los errores de capa del dominio.