survey-webapp/SurveyBackend/SurveyBackend.API/Middlewares/ExceptionsMiddleware.cs
2025-04-27 16:06:17 +05:00

61 lines
No EOL
1.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using SurveyBackend.Services.Exceptions;
namespace SurveyBackend.Middlewares;
/// <summary>
/// Имбовая миддлваря, ловит все эксепшны, кастомные прокидывает как HTTP-exception, остальные кидает 502 и кайфуем
/// </summary>
public class ExceptionsMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionsMiddleware> _logger;
/// <summary>
/// Ну типа конструктор хз
/// </summary>
/// <param name="next"></param>
/// <param name="logger"></param>
public ExceptionsMiddleware(RequestDelegate next, ILogger<ExceptionsMiddleware> logger)
{
_next = next;
_logger = logger;
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (ServiceException ex)
{
context.Response.StatusCode = ex.StatusCode;
context.Response.ContentType = "application/json";
var response = new
{
error = ex.Message
};
await context.Response.WriteAsJsonAsync(response);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
var response = new
{
error = "Internal Server Error. GG WP, request bub fix"
};
await context.Response.WriteAsJsonAsync(response);
}
}
}