Exception middleware ya esta bien implementado
This commit is contained in:
@@ -1,5 +1,5 @@
|
|||||||
using CleanArchitecture.API.Errors;
|
using CleanArchitecture.API.Errors;
|
||||||
using System.Net;
|
using CleanArchitecture.Application.Exceptions;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace CleanArchitecture.API.Middlewares
|
namespace CleanArchitecture.API.Middlewares
|
||||||
@@ -27,16 +27,34 @@ namespace CleanArchitecture.API.Middlewares
|
|||||||
{
|
{
|
||||||
_logger.LogError(ex, ex.Message);
|
_logger.LogError(ex, ex.Message);
|
||||||
context.Response.ContentType = "application/json";
|
context.Response.ContentType = "application/json";
|
||||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
var statusCode = StatusCodes.Status500InternalServerError;
|
||||||
|
var result = string.Empty;
|
||||||
|
|
||||||
var response = _env.IsDevelopment() ?
|
switch (ex)
|
||||||
new CodeErrorException((int)HttpStatusCode.InternalServerError, ex.Message, ex.StackTrace)
|
{
|
||||||
: new CodeErrorException((int)HttpStatusCode.InternalServerError);
|
case NotFoundException notFoundException:
|
||||||
|
statusCode = StatusCodes.Status404NotFound;
|
||||||
|
break;
|
||||||
|
case ValidationException validationException:
|
||||||
|
statusCode = StatusCodes.Status400BadRequest;
|
||||||
|
var validationJson = JsonSerializer.Serialize(validationException.Errors);
|
||||||
|
result = JsonSerializer.Serialize(new CodeErrorException(statusCode, ex.Message, validationJson));
|
||||||
|
break;
|
||||||
|
case BadRequestException badRequestException:
|
||||||
|
statusCode = StatusCodes.Status400BadRequest;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
|
if(string.IsNullOrEmpty(result))
|
||||||
var json = JsonSerializer.Serialize(response, options);
|
{
|
||||||
|
result = JsonSerializer.Serialize(new CodeErrorException(statusCode, ex.Message, ex.StackTrace));
|
||||||
|
}
|
||||||
|
|
||||||
await context.Response.WriteAsync(json);
|
context.Response.StatusCode = statusCode;
|
||||||
|
|
||||||
|
await context.Response.WriteAsync(result);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
|
||||||
|
namespace CleanArchitecture.Application.Exceptions
|
||||||
|
{
|
||||||
|
public class BadRequestException: ApplicationException
|
||||||
|
{
|
||||||
|
public BadRequestException(string message): base(message)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user