【发布时间】: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