mirror of
https://github.com/azaion/admin.git
synced 2026-04-22 05:26:34 +00:00
88c7b288df
Made-with: Cursor
45 lines
1.5 KiB
C#
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;
|
|
}
|
|
} |