prueba tecnica
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
using ProximaContracts.Shared.Exceptions.Repositories.Contract;
|
||||
using ProximaContracts.Shared.Exceptions.Repositories.Rates;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||
|
||||
namespace ProximaContracts.API.Middleware
|
||||
{
|
||||
public sealed 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)
|
||||
{
|
||||
|
||||
_logger.LogError(ex, "Unhandled exception");
|
||||
await HandleExceptionAsync(context, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static Task HandleExceptionAsync(HttpContext ctx, Exception ex)
|
||||
{
|
||||
|
||||
(HttpStatusCode code, string title) mapping = ex switch
|
||||
{
|
||||
GetContractByIdException => (HttpStatusCode.InternalServerError, "Error getting contract by Id."),
|
||||
GetContractsException => (HttpStatusCode.InternalServerError, "Error getting all contracts."),
|
||||
CreateContractException => (HttpStatusCode.InternalServerError, "Error creating contract."),
|
||||
CreateContractRateNotFoundException => (HttpStatusCode.BadRequest, "Error creating contract =>Rate not found."),
|
||||
UpdateContractException => (HttpStatusCode.InternalServerError, "Error updating contract."),
|
||||
CheckIfRateIdExistsException =>(HttpStatusCode.InternalServerError, "Error checking rates."),
|
||||
GetAllRatesException => (HttpStatusCode.InternalServerError, "Error getting all rates."),
|
||||
GetAllRates404Exception =>(HttpStatusCode.NotFound, "No Rates found."),
|
||||
_ => (HttpStatusCode.InternalServerError, $"Internal server error.")
|
||||
};
|
||||
|
||||
var problem = new
|
||||
{
|
||||
type = $"https://httpstatuses.com/{(int)mapping.code}",
|
||||
title = mapping.title,
|
||||
status = (int)mapping.code,
|
||||
detail = ex.Message,
|
||||
instance = ctx.Request.Path
|
||||
};
|
||||
|
||||
string json = JsonSerializer.Serialize(problem);
|
||||
ctx.Response.ContentType = "application/problem+json";
|
||||
ctx.Response.StatusCode = (int)mapping.code;
|
||||
return ctx.Response.WriteAsync(json);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user