using CarParkValidationAPI.Entities; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Net; using System.Text.Json; using System.Threading.Tasks; namespace CarParkValidationAPI.Helpers { public class ErrorHandlerMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; private readonly IHostEnvironment _env; public ErrorHandlerMiddleware(RequestDelegate next, ILogger logger, IHostEnvironment env) { _next = next; _logger = logger; _env = env; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { var response = context.Response; response.ContentType = "application/json"; _logger.LogError(ex, ex.Message); /* switch (ex) { // case Exception e: // // custom application error // response.StatusCode = (int)HttpStatusCode.BadRequest; // break; case KeyNotFoundException: // not found error response.StatusCode = (int)HttpStatusCode.NotFound; break; default: // unhandled error response.StatusCode = (int)HttpStatusCode.InternalServerError; break; } */ response.StatusCode = ex switch { // case Exception e: // // custom application error // response.StatusCode = (int)HttpStatusCode.BadRequest; // break; KeyNotFoundException => (int)HttpStatusCode.NotFound,// not found error _ => (int)HttpStatusCode.InternalServerError,// unhandled error }; //response.StatusCode = (int)HttpStatusCode.InternalServerError; var res = _env.IsDevelopment() ? new ApiException(response.StatusCode, ex.Message, ex.StackTrace?.ToString()) : new ApiException(response.StatusCode, "Internal Server Error"); var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var json = JsonSerializer.Serialize(res, options); await response.WriteAsync(json); } } } }