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 + })); } }