diff --git a/DrinkRateAPI/Exceptions/ExceptionHandlingMiddleware.cs b/DrinkRateAPI/Exceptions/ExceptionHandlingMiddleware.cs new file mode 100644 index 0000000..e4e4740 --- /dev/null +++ b/DrinkRateAPI/Exceptions/ExceptionHandlingMiddleware.cs @@ -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 _logger; + + public ExceptionHandlingMiddleware(RequestDelegate next, ILogger 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); + } +} \ No newline at end of file diff --git a/DrinkRateAPI/Exceptions/Exceptions.cs b/DrinkRateAPI/Exceptions/Exceptions.cs index 14c8432..c005b85 100644 --- a/DrinkRateAPI/Exceptions/Exceptions.cs +++ b/DrinkRateAPI/Exceptions/Exceptions.cs @@ -1,7 +1,38 @@ namespace DrinkRateAPI.Exceptions; -public class DrinkRateException : Exception; +public abstract class DrinkRateException : Exception; +/// +/// 400 - Bad request +/// +public class BadRequestException : DrinkRateException; + +/// +/// 401 - Unauthenticated +/// +public class UnauthenticatedException : DrinkRateException; + +/// +/// 402 - Payment required +/// +public class PaymentRequiredException : DrinkRateException; + +/// +/// 403 - Forbidden +/// +public class ForbiddenException : DrinkRateException; + +/// +/// 404 - Not found +/// public class NotFoundException : DrinkRateException; -public class UnauthorizedException : DrinkRateException; \ No newline at end of file +/// +/// 418 - I'm a teapot +/// +public class IamATeapotException : DrinkRateException; + +/// +/// 451 - Unavailable for lagal reasons +/// +public class UnavailableForLagalReasonsException : DrinkRateException; \ No newline at end of file