Files
admin/Azaion.AdminApi/BusinessExceptionHandler.cs
Oleksandr Bezdieniezhnykh 88c7b288df [AZ-199] [AZ-200] [AZ-201] [AZ-202] Fix API bugs
Made-with: Cursor
2026-04-16 06:55:11 +03:00

45 lines
1.5 KiB
C#

using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Azaion.Common;
public class BusinessExceptionHandler(ILogger<BusinessExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
if (exception is BusinessException ex)
{
logger.LogWarning(exception, ex.Message);
httpContext.Response.StatusCode = StatusCodes.Status409Conflict;
httpContext.Response.ContentType = "application/json";
var err = JsonConvert.SerializeObject(new
{
ErrorCode = ex.ExceptionEnum,
ex.Message
});
await httpContext.Response.WriteAsync(err, cancellationToken).ConfigureAwait(false);
return true;
}
if (exception is BadHttpRequestException badReq)
{
logger.LogWarning(exception, badReq.Message);
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
httpContext.Response.ContentType = "application/json";
var err = JsonConvert.SerializeObject(new
{
ErrorCode = 0,
badReq.Message
});
await httpContext.Response.WriteAsync(err, cancellationToken).ConfigureAwait(false);
return true;
}
return false;
}
}