forked from mtusi2026/mtusi2026lab2
29 lines
1.0 KiB
C#
29 lines
1.0 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 (Exception exception) when (exception is NpgsqlException or SocketException or TimeoutException)
|
|
{
|
|
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);
|
|
}
|
|
}
|
|
}
|