using System.Net; using FindAndDrive.Domain.Models.Exceptions; using Newtonsoft.Json; namespace FindAndDrive.API.Middleware; public class ExceptionMiddleware { private readonly ILoggerFactory _loggerFactory; private readonly RequestDelegate _requestDelegate; public ExceptionMiddleware(RequestDelegate requestDelegate, ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; _requestDelegate = requestDelegate; } public async Task InvokeAsync(HttpContext httpContext) { try { await _requestDelegate(httpContext); } catch (Exception e) { var _logger = _loggerFactory.CreateLogger(); if (httpContext.Request.Path.HasValue) { _logger.LogError(e, "{PathValue} threw an error", httpContext.Request.Path.Value); } await HandleError(httpContext, e); } } private static async Task HandleError(HttpContext httpContext, Exception e) { var response = new ApiException(); httpContext.Response.ContentType = "application/json"; if (e is PredictionAlreadyExistsException predictionAlreadyExistsException) { httpContext.Response.StatusCode = (int)HttpStatusCode.Conflict; response = new ApiException { Message = predictionAlreadyExistsException.Message, StatusCode = httpContext.Response.StatusCode }; } else if(e is GatewayErrorException gatewayErrorException) { httpContext.Response.StatusCode = (int)HttpStatusCode.GatewayTimeout; response = new ApiException { Message = gatewayErrorException.Message, StatusCode = httpContext.Response.StatusCode }; } else if (e is BadRequestException badRequestException) { httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; response = new ApiException { Message = badRequestException.Message, StatusCode = httpContext.Response.StatusCode }; } else { httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; response = new ApiException { Message = "Something went wrong", StatusCode = httpContext.Response.StatusCode }; } await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(response)); } }