Merge branch 'Sec_15_Middleware_ASPNET/66_Middleware_Exception_Tipado' into dev
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
using CleanArchitecture.API.Errors;
|
||||
using System.Net;
|
||||
using CleanArchitecture.Application.Exceptions;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace CleanArchitecture.API.Middlewares
|
||||
@@ -27,16 +27,34 @@ namespace CleanArchitecture.API.Middlewares
|
||||
{
|
||||
_logger.LogError(ex, ex.Message);
|
||||
context.Response.ContentType = "application/json";
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
var statusCode = StatusCodes.Status500InternalServerError;
|
||||
var result = string.Empty;
|
||||
|
||||
var response = _env.IsDevelopment() ?
|
||||
new CodeErrorException((int)HttpStatusCode.InternalServerError, ex.Message, ex.StackTrace)
|
||||
: new CodeErrorException((int)HttpStatusCode.InternalServerError);
|
||||
switch (ex)
|
||||
{
|
||||
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 };
|
||||
var json = JsonSerializer.Serialize(response, options);
|
||||
if(string.IsNullOrEmpty(result))
|
||||
{
|
||||
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