say NO to try-catch in controllers

- added ExceptionsMiddleware.cs
- added more Exception types
- removed all exceptions logic in controllers
This commit is contained in:
Вячеслав 2025-04-18 15:15:32 +05:00
parent eb271793ad
commit 55e82425a9
8 changed files with 75 additions and 20 deletions

View file

@ -0,0 +1,49 @@
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);
}
}
}