全局捕获FAST API中的`Exception` [英] Catch `Exception` in fast api globally
本文介绍了全局捕获FAST API中的`Exception`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是一个非常新的蟒蛇和Fastapi。
我正在尝试在全球级别捕获未处理的异常。因此,我在main.py
文件中的某个位置写下了以下内容:
@app.exception_handler(Exception)
async def exception_callback(request: Request, exc: Exception):
logger.error(exc.detail)
但上述方法永远不会执行。 但如果我编写一个自定义异常并尝试捕获它(如下所示),它就能很好地工作。
class MyException(Exception):
#some code
@app.exception_handler(MyException)
async def exception_callback(request: Request, exc: MyException):
logger.error(exc.detail)
我已经经历了Catch exception type of Exception and process body request #575。但是这个错误涉及到访问请求正文。看到这个BUG后,我觉得应该可以抓到Exception
。
FastApi版本fastapi>=0.52.0
。
提前感谢:)
推荐答案
如果要捕获所有未处理的异常(内部服务器错误),有一种非常简单的方法。Documentation
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response
app = FastAPI()
async def catch_exceptions_middleware(request: Request, call_next):
try:
return await call_next(request)
except Exception:
# you probably want some kind of logging here
return Response("Internal server error", status_code=500)
app.middleware('http')(catch_exceptions_middleware)
请确保将此中间件放在第一位。
这篇关于全局捕获FAST API中的`Exception`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文