Refactor ExceptionHandlingMiddleware responses

Refactored `ExceptionHandlingMiddleware` to use `ValidationProblemDetails` for structured and consistent error responses. Marked the middleware as obsolete with a recommendation to use `DigitalData.Core.Exceptions.Middleware`. Updated exception handling logic to replace error message strings with detailed problem descriptions, including titles and details for each exception type. Improved the default case for unhandled exceptions with a user-friendly message. Enhanced response serialization using `WriteAsJsonAsync`.
This commit is contained in:
tekh 2025-12-03 17:08:12 +01:00
parent bf98efd3a3
commit 4ed080f58a

View File

@ -11,7 +11,7 @@ namespace ReC.API.Middleware;
/// <summary> /// <summary>
/// Middleware for handling exceptions globally in the application. /// Middleware for handling exceptions globally in the application.
/// Captures exceptions thrown during the request pipeline execution, /// Captures exceptions thrown during the request pipeline execution,
/// logs them, and returns an appropriate HTTP response with a JSON error message. /// logs them, and returns an appropriate HTTP response with a JSON error details.
/// </summary> /// </summary>
[Obsolete("Use DigitalData.Core.Exceptions.Middleware")] [Obsolete("Use DigitalData.Core.Exceptions.Middleware")]
public class ExceptionHandlingMiddleware public class ExceptionHandlingMiddleware
@ -58,13 +58,17 @@ public class ExceptionHandlingMiddleware
{ {
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
string? message = null; ValidationProblemDetails? details = null;
switch (exception) switch (exception)
{ {
case BadRequestException badRequestEx: case BadRequestException badRequestEx:
context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
message = badRequestEx.Message; details = new()
{
Title = "Bad Request",
Detail = badRequestEx.Message
};
break; break;
case ValidationException validationEx: case ValidationException validationEx:
@ -74,37 +78,46 @@ public class ExceptionHandlingMiddleware
.GroupBy(e => e.PropertyName, e => e.ErrorMessage) .GroupBy(e => e.PropertyName, e => e.ErrorMessage)
.ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray()); .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray());
await context.Response.WriteAsJsonAsync(new ValidationProblemDetails() details = new ValidationProblemDetails()
{ {
Title = "Validation failed", Title = "Validation failed",
Errors = validationEx.Errors Errors = validationEx.Errors
.GroupBy(e => e.PropertyName, e => e.ErrorMessage) .GroupBy(e => e.PropertyName, e => e.ErrorMessage)
.ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray()), .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray()),
}); };
break; break;
case NotFoundException notFoundEx: case NotFoundException notFoundEx:
context.Response.StatusCode = (int)HttpStatusCode.NotFound; context.Response.StatusCode = (int)HttpStatusCode.NotFound;
message = notFoundEx.Message; details = new()
{
Title = "Not Found",
Detail = notFoundEx.Message
};
break; break;
case DataIntegrityException dataIntegrityEx: case DataIntegrityException dataIntegrityEx:
context.Response.StatusCode = (int)HttpStatusCode.Conflict; context.Response.StatusCode = (int)HttpStatusCode.Conflict;
message = dataIntegrityEx.Message; details = new()
{
Title = "Data Integrity Violation",
Detail = dataIntegrityEx.Message
};
break; break;
default: default:
logger.LogError(exception, "Unhandled exception occurred."); logger.LogError(exception, "Unhandled exception occurred.");
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
message = "An unexpected error occurred."; details = new()
{
Title = "Internal Server Error",
Detail = "An unexpected error occurred. Please try again later."
};
break; break;
} }
if (message is not null) if (details is not null)
await context.Response.WriteAsync(JsonSerializer.Serialize(new await context.Response.WriteAsJsonAsync(details);
{
message
}));
} }
} }