43 lines
1.8 KiB
C#
43 lines
1.8 KiB
C#
using FluentValidation;
|
|
using Helpdesk.Application.Common;
|
|
using Microsoft.AspNetCore.Diagnostics;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace Helpdesk.Api.Infrastructure;
|
|
|
|
/// <summary>Převod výjimek na ProblemDetails (RFC 9457): aplikační chyby → 4xx, validace → 400 se seznamem chyb.</summary>
|
|
internal sealed class AppExceptionHandler(IProblemDetailsService problemDetails) : IExceptionHandler
|
|
{
|
|
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
|
|
{
|
|
ProblemDetails? problem = exception switch
|
|
{
|
|
ValidationException validation => new ValidationProblemDetails(
|
|
validation.Errors
|
|
.GroupBy(e => JsonName(e.PropertyName))
|
|
.ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray()))
|
|
{
|
|
Status = StatusCodes.Status400BadRequest,
|
|
Title = "Neplatná vstupní data.",
|
|
},
|
|
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message },
|
|
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
|
|
_ => null,
|
|
};
|
|
|
|
if (problem is null)
|
|
return false; // neočekávaná chyba → výchozí 500 bez detailů
|
|
|
|
httpContext.Response.StatusCode = problem.Status!.Value;
|
|
return await problemDetails.TryWriteAsync(new ProblemDetailsContext
|
|
{
|
|
HttpContext = httpContext,
|
|
ProblemDetails = problem,
|
|
Exception = exception,
|
|
});
|
|
}
|
|
|
|
private static string JsonName(string propertyName) =>
|
|
string.IsNullOrEmpty(propertyName) ? propertyName : char.ToLowerInvariant(propertyName[0]) + propertyName[1..];
|
|
}
|