async def validation_exception_handler(request, exc: RequestValidationError): """ Validation exception handler with localization """ for error in exc.errors(): error['msg'] = lazy_gettext(error['msg']) response = TranslateJsonResponse( {"detail": exc.errors()}, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY) return response.translate_content(request.state.gettext)
async def validation_exception_handler(request: Request, exc: RequestValidationError): print(jsonable_encoder({"detail": exc.errors(), "body": exc.body})) return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({ "detail": exc.errors(), "body": exc.body }), )
async def handle_validation_error( request: Request, exc: RequestValidationError, ) -> Response: print(f"Validation error on {request.url}", "\n", exc.errors()) return Response( content=orjson.dumps(exc.errors()), status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, )
async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder({ "message": "An error occurred", "loc": exc.errors()[0]["loc"], "detail": exc.errors()[0]["msg"] }), )
async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( # by default FastAPI responds with 422 on request validation errors, we want good ol' 400 status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder({ "detail": exc.errors(), # DEMO: transform errors "demo_errors": [{ ".".join(error["loc"]): {error["msg"]} } for error in exc.errors()], }), )
async def handle_request_validation_error(request: Request, exc: RequestValidationError): logger.error(exc) # 自定义异常提示 msg = set() for err in exc.errors(): if err['type'] == "value_error.paramsvalue": msg.add(err['msg']) resp = {} if not isFormalSystem: resp = exc.errors() return comm_ret(code=resp_code.PARAMETER_ERROR, msg="\n".join(msg) or "请求参数异常", resp=resp)
async def validation_exception_handler(request: Request, exc: RequestValidationError): """ 捕获请求参数 验证错误 :param request: :param exc: :return: """ data = exc.errors()[0]["msg"] print(traceback.format_exc()) logger.error( f"参数错误\nURL:{request.url}\nHeaders:{request.headers}\n{exc.errors()[0]['loc']}\n{data}" ) return ValidationErrorResponse(content=exc.errors()[0]['loc'])
async def validation_exception_handler( request: Request, exc: RequestValidationError ): return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder({"errors": exc.errors()}), )
def _build_errors(cls, ex: RequestValidationError) -> list: errors = [] for error in ex.errors(): _, _, field = error.get('loc') message = error.get('msg') errors.append(Error.of(field, message)) return errors
def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={"detail": exc.errors()}, )
async def validation_exception_handler(request: Request, exc: RequestValidationError): json_error = JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}) ) print("WARN - Estructura invalida - {}".format(json_error)) return json_error
async def validation_exception_handler(request: Request, exc: RequestValidationError): error_id = str(uuid4()) headers = getattr(exc, 'headers', None) response_data = {'detail': exc.errors(), 'error_id': error_id} await _generate_log(error_id, request, 422, exc) return await _generate_response(headers, response_data, 422)
def make_outcome(request: Request, exc: RequestValidationError): """ https://terminology.hl7.org/2.0.0/CodeSystem-operation-outcome.html :param exc: :param status_code: :return: """ klass = lookup_fhir_class( "OperationOutcome", fhir_release=request.scope["FHIR_VERSION"] ) issues = list() for error in exc.errors(): issue = { "severity": "error", "code": exc.code, "details": { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/operation-outcome", "code": exc.system_code, "display": exc.body, } ] }, "diagnostics": f"loc: {error['loc']}, message: {error['msg']}", } issues.append(issue) outcome = klass(**{"id": str(request.scope["FHIR_REQUEST_ID"]), "issue": issues}) return outcome
async def validation_exception_handler_error( request: Request, exc: RequestValidationError ): error_out = utils.convert_error_pydantic(exc.errors()) return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={"error": error_out, "status": "failed"}, )
async def handle_validation_error(request, exc: RequestValidationError): return JSONResponse( { 'error': ErrorType.VALIDATION_ERROR, 'detail': exc.errors(), }, status_code=422, )
def override_fastapi_default_422_response_with_400_on_invalid_payloads( request: Request, exception: RequestValidationError, ) -> None: return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={'detail': exception.errors()}, )
def validation_exception_handler(request, exc: RequestValidationError): error_code = 1000 print(generate_error_message(error_code), exc) return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=generate_error_content(error_code=error_code, error_detail=exc.errors()), )
async def validation_execption_handler(request: Request, exc: RequestValidationError): """Adjust validation error output to conform to schema""" detail = [] for err in exc.errors(): if "loc" in err: err["loc"] = (str(v) for v in err["loc"]) # sometimes not string detail.append(err) return JSONResponse(status_code=422, content=jsonable_encoder({"detail": detail}))
async def validation_exception_handler(request: Request, exc: RequestValidationError): res = [] for error_obj in exc.errors(): res.append({error_obj['loc'][-1]: error_obj['msg']}) return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, content=BaseResponse.error_response( error=res, status=status.HTTP_400_BAD_REQUEST))
async def request_validation_exception_handler(request: Request, exc: RequestValidationError): logger.error(f"参数错误{request.method} {request.url}") return JSONResponse( { "code": status.HTTP_400_BAD_REQUEST, "message": "请求参数校验异常", "data": exc.errors() } )
async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder( JSONApiErrorResponse(errors=[ create_bad_request_error(error) for error in exc.errors() ])), )
def handle_422(req: Request, exc: RequestValidationError): errs = {'errors': []} print('errs ', exc.errors()) print('err body ', exc.body) if not exc.body: errs['errors'].append('Request body is empty') else: for err in exc.errors(): err_field_name = err['loc'][-1] err_field_value = exc.body.get(err_field_name, err_field_name) if err_field_name == err_field_value: errs['errors'].append(f"{err_field_name} - {err['msg']}") else: errs['errors'].append( f"{err_field_name}: ({err_field_value}) - {err['msg']}") return JSONResponse(errs, status_code=HTTP_422_UNPROCESSABLE_ENTITY)
async def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={ "detail": jsonable_encoder(exc.errors()) }, )
async def request_validation_exception_handler( request: Request, exc: RequestValidationError) -> JSONResponse: # Log the error that is send to the client logging.debug(f"Body of failed request: {exc.body}") logging.info( "Error thrown on request", extra={ "url": request.url, "error_detail": jsonable_encoder(exc.errors()) }, ) return JSONResponse( status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={ "detail": jsonable_encoder(exc.errors()), "body": exc.body }, )
def validation_exception(request: Request, exc: exceptions.RequestValidationError): return responses.JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=encoders.jsonable_encoder({ "detail": exc.errors(), "body": exc.body }), )
async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({ "detail": exc.errors(), "Error": "Name field is missing" }), )
async def request_validation_exception_handler(request: Request, exc: RequestValidationError): """ 请求参数验证异常 :param request: :param exc: :return: """ logger.error(f"请求参数格式错误\nURL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc()}") return response_code.resp_422(message=exc.errors())
def type_error_handler(request: Request, exc: RequestValidationError) -> UJSONResponse: return UJSONResponse( status_code=422, content={ 'ok': False, 'error': exc.errors() }, headers=DEFAULT_ERROR_HEADERS, )
def handle_validation_error(request: Request, exc: RequestValidationError) -> JSONResponse: status = 400 title = 'Bad Request' msg = 'Cannot or will not process the request due to request being malformed.' loc = exc.errors()[0]['loc'] msg = exc.errors()[0]['msg'] response = create_error_response(status, title, loc, msg, request.url.path) return JSONResponse(status_code=status, content=response.to_dict())
async def api_validation_exception(request: Request, exc: RequestValidationError): print(traceback.print_exc()) return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, content={ "title": "Validation error occurred", "details": str(exc.errors()), "body": str(exc.body) }, headers={"x-request-id": request.state.request_id})