Files
admin/Azaion.Api/BusinessExceptionHandler.cs
T
Alex Bezdieniezhnykh 55f4e8b3a6 add exceptions handler
2025-04-17 00:27:56 +03:00

28 lines
925 B
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 not BusinessException ex)
return false;
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;
}
}