FastAPI 异步/等待异常处理与路由

时间:2021-07-29 16:50:07

标签: exception async-await fastapi

我有以下类作为我的 FastAPI 应用程序的异常处理程序:

class RouteHandler(APIRoute):
    def get_route_handler(self) -> Callable:
        route_handler = super().get_route_handler()

        async def custom_handler(request: Request) -> Response:
            try:
                response: Response = await route_handler(request)
                return response
            except:
                exc_type, exc_obj, tb = sys.exc_info()
                f = tb.tb_frame
                lineno = tb.tb_lineno
                filename = tb.tb_frame.f_code.co_filename
                linecache.checkcache(filename)
                line = linecache.getline(filename, lineno, f.f_globals)
                logger.debug(f'EXCEPTION IN ({filename}, LINE {lineno} "{ line.strip()}"): {exc_obj}')
                raise HTTPException(status_code=500)
        return custom_handler

当请求对象有某种类型的异常时,代码用于显示实际原因是什么,例如我可以看到它是 TypeErrorNameError 还是任何实际问题是。我在回溯中找不到的是实际错误的来源 - 文件名/ lineno 和 line 都指向我的处理程序文件和 response: Response = await route_handler(request) 代码块。有没有办法提取导致实际异常的位置?我曾尝试关注 tb_next,但它从未真正进入我的路由器文件。

0 个答案:

没有答案