32 lines
859 B
C#
32 lines
859 B
C#
using MemeVault.Domain.Exceptions;
|
|||
|
|
using Microsoft.AspNetCore.Diagnostics;
|
||
|
|
using Microsoft.AspNetCore.Mvc;
|
||
|
|
|
||
|
|
namespace MemeVault.Api.Middleware;
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Конвертирует DomainException в 400 Problem Details.
|
||
|
|
/// </summary>
|
||
|
|
public sealed class DomainExceptionHandler : IExceptionHandler
|
||
|
|
{
|
||
|
|
public async ValueTask<bool> TryHandleAsync(
|
||
|
|
HttpContext ctx,
|
||
|
|
Exception ex,
|
||
|
|
CancellationToken ct)
|
||
|
|
{
|
||
|
|
if (ex is not DomainException domain)
|
||
|
|
return false;
|
||
|
|
|
||
|
|
var problem = new ProblemDetails
|
||
|
|
{
|
||
|
|
Title = "Business rule violation",
|
||
|
|
Detail = domain.Message,
|
||
|
|
Status = StatusCodes.Status400BadRequest,
|
||
|
|
};
|
||
|
|
|
||
|
|
ctx.Response.StatusCode = problem.Status!.Value;
|
||
|
|
await ctx.Response.WriteAsJsonAsync(problem, ct);
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|