diff --git a/src/ReC.API/Middleware/ExceptionHandlingMiddleware.cs b/src/ReC.API/Middleware/ExceptionHandlingMiddleware.cs index 577be6b..cfac814 100644 --- a/src/ReC.API/Middleware/ExceptionHandlingMiddleware.cs +++ b/src/ReC.API/Middleware/ExceptionHandlingMiddleware.cs @@ -11,7 +11,7 @@ namespace ReC.API.Middleware; /// /// 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. /// [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); } }