forked from mtusi2026/mtusi2026lab5
43 lines
1.8 KiB
C#
43 lines
1.8 KiB
C#
using Messenger.Api.Services;
|
|
using System.Net.Sockets;
|
|
using Npgsql;
|
|
|
|
namespace Messenger.Api.Middleware;
|
|
|
|
public sealed class ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
|
|
{
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await next(context);
|
|
}
|
|
catch (AttachmentException exception)
|
|
{
|
|
if(!context.Response.HasStarted)
|
|
await ApiSupport.ApiError(context,exception.Status,exception.Code,exception.Message).ExecuteAsync(context);
|
|
}
|
|
catch (OperationCanceledException) when (!context.RequestAborted.IsCancellationRequested)
|
|
{
|
|
if(!context.Response.HasStarted)
|
|
await ApiSupport.ApiError(context,503,"unavailable","Время ожидания истекло").ExecuteAsync(context);
|
|
}
|
|
catch (BadHttpRequestException exception) when(exception.StatusCode==413)
|
|
{
|
|
await ApiSupport.ApiError(context,413,"payload_too_large","Слишком большой запрос").ExecuteAsync(context);
|
|
}
|
|
catch (Exception exception) when (exception is NpgsqlException or SocketException or TimeoutException or Amazon.S3.AmazonS3Exception or HttpRequestException)
|
|
{
|
|
logger.LogError(exception, "Database request failed");
|
|
if (!context.Response.HasStarted)
|
|
await ApiSupport.ApiError(context, 503, "unavailable", "Сервис временно недоступен").ExecuteAsync(context);
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
logger.LogError(exception, "Request failed");
|
|
if (!context.Response.HasStarted)
|
|
await ApiSupport.ApiError(context, 500, "internal_error", "Внутренняя ошибка").ExecuteAsync(context);
|
|
}
|
|
}
|
|
}
|