public static IApplicationBuilder ConfigureExceptionHandler(this IApplicationBuilder app) { app.UseExceptionHandler(appError => { appError.Run(async context => { var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>(); var exception = exceptionHandlerPathFeature.Error; ErrorResponseWrapper <string> error = new ErrorResponseWrapper <string>(); switch (exception) { case FormatException formatException: error.ErrorMessage = formatException.Message; break; default: error.ErrorMessage = "Erro inesperado."; break; } var result = JsonSerializer.Serialize(error); context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status500InternalServerError; await context.Response.WriteAsync(result); }); }); return(app); }
public IActionResult Handle(ControllerBase controller, object result = default) { if (controller == null) { return(null); } if (!this.notificationContext.HasNotifications) { return(controller.Ok(result)); } var errorResponse = new ErrorResponseWrapper <object>(); errorResponse.Value = result; errorResponse.Errors = new List <KeyValuePair <string, string> >(this.notificationContext.Notifications.Select(n => new KeyValuePair <string, string>(n.Key, n.Message))); errorResponse.ErrorMessage = "Um ou mais erros ocorreram"; if (this.notificationContext.Notifications.Any(n => n.Key == NotificationKeys.NotFound)) { return(controller.NotFound(errorResponse)); } else if (this.notificationContext.Notifications.Any(n => n.Key == NotificationKeys.InvalidArgument)) { return(controller.UnprocessableEntity(errorResponse)); } else if (this.notificationContext.Notifications.Any(n => n.Key == NotificationKeys.AlreadyExists)) { return(controller.Conflict(errorResponse)); } return(controller.StatusCode(StatusCodes.Status500InternalServerError, errorResponse)); }