如何将自定义异常处理与 FastAPI 异常处理集成?

问题描述 投票:0回答:2

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)

我使用上述方法遇到的问题是无法将消息作为参数传递。

对整个主题有什么想法吗?

python python-3.x exception fastapi
2个回答
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)

通过这种方式,您可以引发任何异常、任何状态代码和任何消息,并在 JSON 响应中包含

message

FastAPI docs 上有详细解释


6
投票
您可以添加

自定义异常处理程序,并使用 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
 实例。示例:

app.add_exception_handler(MyException, my_exception_handler)
将异常处理程序添加到 

app

 实例的另一种方法是使用 FastAPI 类的 
exception_handlers
 参数,如
这个答案中所示。相关答案也可以在这里这里找到。

© www.soinside.com 2019 - 2024. All rights reserved.