Add more exceptions

This commit is contained in:
Jiří Vrabec 2025-08-11 07:56:11 +02:00
parent 8058add053
commit ae723cecaf
2 changed files with 80 additions and 2 deletions

View file

@ -0,0 +1,47 @@
using System.Net;
namespace DrinkRateAPI.Exceptions;
public record ExceptionResponse(HttpStatusCode StatusCode, string Description);
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
_logger.LogError(exception, "An unexpected error occurred.");
ExceptionResponse response = exception switch
{
ApplicationException _ => new ExceptionResponse(HttpStatusCode.BadRequest, "Application exception occurred."),
KeyNotFoundException _ => new ExceptionResponse(HttpStatusCode.NotFound, "The request key not found."),
UnauthorizedAccessException _ => new ExceptionResponse(HttpStatusCode.Unauthorized, "Unauthorized."),
_ => new ExceptionResponse(HttpStatusCode.InternalServerError, "Internal server error. Please retry later.")
};
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)response.StatusCode;
await context.Response.WriteAsJsonAsync(response);
}
}

View file

@ -1,7 +1,38 @@
namespace DrinkRateAPI.Exceptions;
public class DrinkRateException : Exception;
public abstract class DrinkRateException : Exception;
/// <summary>
/// 400 - Bad request
/// </summary>
public class BadRequestException : DrinkRateException;
/// <summary>
/// 401 - Unauthenticated
/// </summary>
public class UnauthenticatedException : DrinkRateException;
/// <summary>
/// 402 - Payment required
/// </summary>
public class PaymentRequiredException : DrinkRateException;
/// <summary>
/// 403 - Forbidden
/// </summary>
public class ForbiddenException : DrinkRateException;
/// <summary>
/// 404 - Not found
/// </summary>
public class NotFoundException : DrinkRateException;
public class UnauthorizedException : DrinkRateException;
/// <summary>
/// 418 - I'm a teapot
/// </summary>
public class IamATeapotException : DrinkRateException;
/// <summary>
/// 451 - Unavailable for lagal reasons
/// </summary>
public class UnavailableForLagalReasonsException : DrinkRateException;