Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从ApiRouter引发异常不会运行异常处理程序,而是返回500内部服务器错误。快速API_Python_Http_Error Handling_Fastapi_Starlette - Fatal编程技术网

Python 从ApiRouter引发异常不会运行异常处理程序,而是返回500内部服务器错误。快速API

Python 从ApiRouter引发异常不会运行异常处理程序,而是返回500内部服务器错误。快速API,python,http,error-handling,fastapi,starlette,Python,Http,Error Handling,Fastapi,Starlette,我使用添加到Fast API的API路由器在Fast API中引发自定义异常。我正在定义异常类和处理程序,并使用以下代码添加它们。这是工作之前,现在我不太清楚是什么问题。添加了中间件,所以这可能就是问题所在 app = FastAPI() origins = [ "*", # Restrict these in the future? ] app.include_router(memblock_router.router) app.include_route

我使用添加到Fast API的API路由器在Fast API中引发自定义异常。我正在定义异常类和处理程序,并使用以下代码添加它们。这是工作之前,现在我不太清楚是什么问题。添加了中间件,所以这可能就是问题所在

app = FastAPI()

origins = [
    "*",    # Restrict these in the future?
]

app.include_router(memblock_router.router)
app.include_router(event_router.router)

app.add_exception_handler(UnauthorizedException, unauthorized_exception_handler)
app.add_exception_handler(InvalidParameterException, invalid_parameter_exception_handler)
app.add_exception_handler(DatabaseException, database_exception_handler)
app.add_exception_handler(ElasticsearchException, elasticsearch_exception_handler)
app.add_exception_handler(ParsingException, parsing_exception_handler)
app.add_exception_handler(ForbiddenErrorMessage, forbidden_error_message_exception)
app.add_exception_handler(UnsupportedErrorMessage, unsupported_message)
app.add_exception_handler(RequestValidationError, validation_exception_handler)

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

我是这样定义异常和处理程序的

class UnauthorizedException(Exception):
    pass

def unauthorized_exception_handler(request: Request, exc: UnauthorizedException):
    print(str(traceback.format_exc()))
    return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED,
                        content={"error": "unauthorized"},
                        headers=get_response_headers())

添加异常中间件
app.add\u中间件(ExceptionMiddleware,handlers=app.exception\u handlers)