survey-webapp/SurveyBackend/SurveyBackend.API/Middlewares/ExceptionsMiddleware.cs
shept 55e82425a9 say NO to try-catch in controllers
- added ExceptionsMiddleware.cs
- added more Exception types
- removed all exceptions logic in controllers
2025-04-18 15:15:32 +05:00

49 lines
No EOL
1.2 KiB
C#

using SurveyBackend.Services.Exceptions;
namespace SurveyBackend.Middlewares;
public class ExceptionsMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionsMiddleware> _logger;
public ExceptionsMiddleware(RequestDelegate next, ILogger<ExceptionsMiddleware> logger)
{
_next = next;
_logger = logger;
}
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);
}
}
}