我有一个包含多个子应用程序的 FastAPI 项目(示例仅包含一个子应用程序)。
main_app = FastAPI()
class CustomException(Exception):
def __init__(self, message: str, status_code: int, name: str = "Exception"):
Exception.__init__(self)
self.name = name
self.status_code = status_code
self.message = message
@main_app.exception_handler(CustomException)
async def custom_exception_handler(exception: CustomException) -> JSONResponse:
return JSONResponse(
status_code=exception.status_code, content={"error": exception.message}
)
main_app.mount("/subapp", subapp1)
我已经处理了主应用程序中的异常,但没有在
subapp1
中处理。现在如果我在 CustomException
中使用 subapp1
:
raise CustomException(
status_code=status.HTTP_404_NOT_FOUND,
message=f"{self.model.__name__} not found",
)
我收到此错误:
运行时错误:捕获已处理的异常,但响应已开始。
似乎在子应用程序中引发
CustomException
时,主应用程序异常处理程序不会处理它。那么如何使用主应用程序异常处理程序处理所有子应用程序的异常?
所以我发现我需要将所有子应用程序添加到异常处理函数中,它解决了我的问题:
def exception_handler(app: FastAPI):
@app.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exception: CustomException) -> JSONResponse:
return JSONResponse(
status_code=exception.status_code, content={"error": exception.message}
)
定义完上述函数后,需要将主应用程序和所有子应用程序发送给它:
exception_handler(app)
exception_handler(subapp1)