diff --git a/Azaion.Api/BusinessExceptionHandler.cs b/Azaion.Api/BusinessExceptionHandler.cs new file mode 100644 index 0000000..18ab6a9 --- /dev/null +++ b/Azaion.Api/BusinessExceptionHandler.cs @@ -0,0 +1,28 @@ + +using Microsoft.AspNetCore.Diagnostics; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; + +namespace Azaion.Common; + +public class BusinessExceptionHandler(ILogger logger) : IExceptionHandler +{ + public async ValueTask 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; + } +} \ No newline at end of file diff --git a/Azaion.Api/Program.cs b/Azaion.Api/Program.cs index 9186e1e..f45b954 100644 --- a/Azaion.Api/Program.cs +++ b/Azaion.Api/Program.cs @@ -1,4 +1,5 @@ using System.Text; +using Azaion.Common; using Azaion.Common.Configs; using Azaion.Common.Database; using Azaion.Common.Entities; @@ -106,6 +107,7 @@ builder.Services.AddLazyCache(); builder.Services.AddScoped(); builder.Services.AddValidatorsFromAssemblyContaining(); +builder.Services.AddExceptionHandler(); var app = builder.Build(); @@ -181,5 +183,6 @@ app.MapPut("/users/queue-offsets/{email}", .RequireAuthorization() .WithOpenApi(op => new OpenApiOperation(op) { Summary = "Updates user queue offsets" }); +app.UseExceptionHandler(_ => {}); app.Run(); diff --git a/Azaion.Common/BusinessException.cs b/Azaion.Common/BusinessException.cs index ae138e4..a149aa1 100644 --- a/Azaion.Common/BusinessException.cs +++ b/Azaion.Common/BusinessException.cs @@ -12,7 +12,7 @@ public class BusinessException(ExceptionEnum exEnum) : Exception(GetMessage(exEn ExceptionDescriptions = EnumExtensions.GetDescriptions(); } - private ExceptionEnum ExceptionEnum { get; set; } = exEnum; + public ExceptionEnum ExceptionEnum { get; set; } = exEnum; public static string GetMessage(ExceptionEnum exEnum) => ExceptionDescriptions.GetValueOrDefault(exEnum) ?? exEnum.ToString(); }