using Messenger.Api.Services; using System.Net.Sockets; using Npgsql; namespace Messenger.Api.Middleware; public sealed class ExceptionHandlingMiddleware(RequestDelegate next, ILogger 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); } } }