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>
/// Middleware for handling exceptions globally in the application.
/// 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>
[Obsolete("Use DigitalData.Core.Exceptions.Middleware")]
public class ExceptionHandlingMiddleware
@ -58,13 +58,17 @@ public class ExceptionHandlingMiddleware
{
context.Response.ContentType = "application/json";
string? message = null;
ValidationProblemDetails? details = null;
switch (exception)
{
case BadRequestException badRequestEx:
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
message = badRequestEx.Message;
details = new()
{
Title = "Bad Request",
Detail = badRequestEx.Message
};
break;
case ValidationException validationEx:
@ -74,37 +78,46 @@ public class ExceptionHandlingMiddleware
.GroupBy(e => e.PropertyName, e => e.ErrorMessage)
.ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray());
await context.Response.WriteAsJsonAsync(new ValidationProblemDetails()
details = new ValidationProblemDetails()
{
Title = "Validation failed",
Errors = validationEx.Errors
.GroupBy(e => e.PropertyName, e => e.ErrorMessage)
.ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray()),
});
};
break;
case NotFoundException notFoundEx:
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
message = notFoundEx.Message;
details = new()
{
Title = "Not Found",
Detail = notFoundEx.Message
};
break;
case DataIntegrityException dataIntegrityEx:
context.Response.StatusCode = (int)HttpStatusCode.Conflict;
message = dataIntegrityEx.Message;
details = new()
{
Title = "Data Integrity Violation",
Detail = dataIntegrityEx.Message
};
break;
default:
logger.LogError(exception, "Unhandled exception occurred.");
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;
}
if (message is not null)
await context.Response.WriteAsync(JsonSerializer.Serialize(new
{
message
}));
if (details is not null)
await context.Response.WriteAsJsonAsync(details);
}
}