public static void UseCustomException(this IApplicationBuilder app) { app.UseExceptionHandler(configure => { configure.Run(async context => { context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; var errorFeature = context.Features.Get <IExceptionHandlerFeature>(); if (errorFeature != null) { var ex = errorFeature.Error; ErrorDTOs errorDTOs = null; if (ex is CustomException) { errorDTOs = new ErrorDTOs(ex.Message, true); } else { errorDTOs = new ErrorDTOs(ex.Message, false); } var response = Response <NoDataDTOs> .Fail(errorDTOs, 500); await context.Response.WriteAsync(JsonSerializer.Serialize(response)); } }); }); }
public static void UseCustomValidationResponse(this IServiceCollection services) { services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = context => { var errors = context.ModelState.Values.Where(ex => ex.Errors.Count > 0).SelectMany(ex => ex.Errors).Select(ex => ex.ErrorMessage); ErrorDTOs errorDTOs = new ErrorDTOs(errors.ToList(), true); var response = Response <NoContentResult> .Fail(errorDTOs, 400); return(new BadRequestObjectResult(response)); }; }); }