rez*_*eza 4 python exception python-3.x fastapi
Python 版本 3.9,FastAPI 版本 0.78.0
我有一个用于应用程序异常处理的自定义函数。当请求遇到内部逻辑问题时,即由于某种原因我想发送 400 的 HTTP 响应,我会调用实用程序函数。
@staticmethod
def raise_error(error: str, code: int) -> None:
    logger.error(error)
    raise HTTPException(status_code=code, detail=error)
不喜欢这种方法。所以我看看
from fastapi import FastAPI, HTTPException, status
from fastapi.respones import JSONResponse
class ExceptionCustom(HTTPException):
    pass
def exception_404_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": "404"})
app.add_exception_handler(ExceptionCustom, exception_404_handler)
我使用上述方法遇到的问题是无法将消息作为参数传递。
对整个主题有什么想法吗?
小智 9
您的自定义异常可以具有您想要的任何自定义属性。假设你这样写:
class ExceptionCustom(HTTPException):
    pass 
在您的自定义处理程序中,您可以执行类似的操作
def exception_404_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": exc.detail})
然后,您需要做的就是以这种方式引发异常:
raise ExceptionCustom(status_code=404, detail='error message')
请注意,您正在为此特定的ExceptionCustom. 如果您需要的只是消息,您可以编写更通用的内容:
class MyHTTPException(HTTPException):
    pass
def my_http_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=exc.status_code, content={"message": exc.detail})
app.add_exception_handler(MyHTTPException, my_http_exception_handler)
通过这种方式,您可以引发任何异常、任何状态代码和任何消息,并将其包含message在 JSON 响应中。
FastAPI 文档中有详细说明
您可以添加自定义异常处理程序,并使用类中的属性Exception(即class MyException(Exception)下面的示例中)来传递您想要这样做的任何消息/变量。异常处理程序(即,@app.exception_handler(MyException)在下面的情况下)将根据您的意愿处理异常并返回您的自定义消息。有关更多选项,请同时查看此相关答案。
要触发以下示例中的异常,请从浏览器访问以下 URL:http://localhost:8000/something
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
class MyException(Exception):
    def __init__(self, name: str):
        self.name = name
app = FastAPI()
@app.exception_handler(MyException)
async def my_exception_handler(request: Request, exc: MyException):
    return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, 
        content={"message": f"{exc.name} cannot be found." })
@app.get("/{name}")
def read_name(name: str):
    if name == "something":
        raise MyException(name=name)
    return {"name": name}
如果您不想使用@app.exception_handler()装饰器,可以从my_exception_handler()函数中删除装饰器,然后使用add_exception_handler()添加方法。例子:
app.add_exception_handler(MyException, my_exception_handler)
将异常处理程序添加到应用程序的另一种方法是使用exception_handlersFastAPI 类的参数,如此处所示。相关答案也可以在这里和这里找到。
| 归档时间: | 
 | 
| 查看次数: | 19673 次 | 
| 最近记录: |