add exceptions handler

This commit is contained in:
Alex Bezdieniezhnykh
2025-04-17 00:27:56 +03:00
parent c1f47f0e8d
commit 55f4e8b3a6
3 changed files with 32 additions and 1 deletions
+28
View File
@@ -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<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;
}
}
+3
View File
@@ -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<ICache, MemoryCache>();
builder.Services.AddValidatorsFromAssemblyContaining<RegisterUserValidator>();
builder.Services.AddExceptionHandler<BusinessExceptionHandler>();
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();