From bf98efd3a35fb5a6b03ba06a366b987e863555dd Mon Sep 17 00:00:00 2001 From: TekH Date: Wed, 3 Dec 2025 15:35:06 +0100 Subject: [PATCH] Improve exception handling and validation responses Updated `ExceptionHandlingMiddleware` to enhance error handling: - Added `Microsoft.AspNetCore.Mvc` and `System.Text.Json` for structured JSON responses. - Made `message` nullable to handle cases without explicit messages. - Refactored `ValidationException` handling: - Changed HTTP status code from 422 to 400. - Grouped validation errors by property and returned them in a `ValidationProblemDetails` object. - Conditionally wrote `message` to the response only if not null. - Improved structure and clarity of validation error responses. --- .../Middleware/ExceptionHandlingMiddleware.cs | 28 ++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/ReC.API/Middleware/ExceptionHandlingMiddleware.cs b/src/ReC.API/Middleware/ExceptionHandlingMiddleware.cs index c770712..577be6b 100644 --- a/src/ReC.API/Middleware/ExceptionHandlingMiddleware.cs +++ b/src/ReC.API/Middleware/ExceptionHandlingMiddleware.cs @@ -1,5 +1,6 @@ using DigitalData.Core.Exceptions; using FluentValidation; +using Microsoft.AspNetCore.Mvc; using ReC.Application.Common.Exceptions; using System.Net; using System.Text.Json; @@ -57,7 +58,7 @@ public class ExceptionHandlingMiddleware { context.Response.ContentType = "application/json"; - string message; + string? message = null; switch (exception) { @@ -67,8 +68,20 @@ public class ExceptionHandlingMiddleware break; case ValidationException validationEx: - context.Response.StatusCode = (int)HttpStatusCode.UnprocessableEntity; - message = "Validation failed: " + string.Join("; ", validationEx.Errors.Select(e => e.ErrorMessage)); + context.Response.StatusCode = (int)HttpStatusCode.BadRequest; + + var errors = validationEx.Errors + .GroupBy(e => e.PropertyName, e => e.ErrorMessage) + .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray()); + + await context.Response.WriteAsJsonAsync(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: @@ -88,9 +101,10 @@ public class ExceptionHandlingMiddleware break; } - await context.Response.WriteAsync(JsonSerializer.Serialize(new - { - message - })); + if (message is not null) + await context.Response.WriteAsync(JsonSerializer.Serialize(new + { + message + })); } }