如何处理FastAPI中所有子应用程序的异常

huangapple go评论66阅读模式
英文:

How to handle exceptions for all the sub apps in FastAPI

问题

I have a FastAPI project containing multiple sub apps (The sample includes just one sub app).

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)

I've handled the exceptions in the main app, but not in subapp1. Now if I use the CustomException in subapp1:

raise CustomException(
status_code=status.HTTP_404_NOT_FOUND,
message=f"{self.model.name} not found",
)

I get this error:

RuntimeError: Caught handled exception, but response already started.

It seems like when raising CustomException in a sub app, it won't be handled by the main app exception handler. So how can I handle the exceptions from all the sub app using the main app exception handler?

英文:

I have a FastAPI project containing multiple sub apps (The sample includes just one sub app).

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)  

I've handled the exceptions in main app, but not in subapp1. Now if I use the CustomException in subapp1:

raise CustomException(
    status_code=status.HTTP_404_NOT_FOUND,
    message=f"{self.model.__name__} not found",
)

I get this error:

> RuntimeError: Caught handled exception, but response already started.

It seems like when raising CustomException in a sub app, it won't be handled by the main app exception handler. So how can I handle the exceptions from all the sub app using the main app exception handler?

答案1

得分: 0

I found out that I need to add all the sub apps to the exception handler function and it fixed my problem:

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}
        )

After defining the above function, the main app and all the sub apps need to be sent to it:

exception_handler(app)
exception_handler(subapp1)
英文:

So I found out that I need to add all the sub apps to the exception handler function and it fixed my problem:

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}
        )

After defining the above function, main app and all the sub apps need to be sent to it:

exception_handler(app)
exception_handler(subapp1)

huangapple
  • 本文由 发表于 2023年4月6日 21:49:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定