private static Task HandleErrorAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; var errorContext = new ServiceErrorContext { Errors = new List <ServiceError>() }; if (exception is ServiceException serviceException) { context.Response.StatusCode = 400; errorContext.Code = "bad_request"; errorContext.Errors.Add(new ServiceError { ErrorMessage = serviceException.Message, }); } else { context.Response.StatusCode = 500; errorContext.Code = "internal_error"; errorContext.Errors.Add(new ServiceError { ErrorMessage = exception.Message }); } return(context.Response.WriteAsync(JsonConvert.SerializeObject(errorContext))); }
public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid) { ServiceErrorContext errorContext = new ServiceErrorContext() { Code = "bad_request", }; var errors = context.ModelState.Values.Where(v => v.Errors.Count > 0) .SelectMany(v => v.Errors) .Select(x => new ServiceError { Exception = x.Exception != null ? x.Exception.ToString() : "", ErrorMessage = x.ErrorMessage }) .ToList(); errorContext.Errors = errors; context.Result = new BadRequestObjectResult(errorContext); } }