【问题标题】:How do I integrate custom exception handling with the FastAPI exception handling?如何将自定义异常处理与 FastAPI 异常处理集成?
【发布时间】:2022-08-09 20:12:39
【问题描述】:

Python 3.9 快速API 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-3.x exception fastapi


    【解决方案1】:

    您可以添加custom exception handlers,并使用Exception 类中的属性来传递您想要这样做的任何消息/变量。下面的例子:

    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}
    

    【讨论】:

      【解决方案2】:

      您的自定义异常可以具有您想要的任何自定义属性。假设你这样写:

      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有详细说明

      【讨论】:

        猜你喜欢
        • 2022-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-14
        • 2011-06-11
        • 2015-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多