FastAPI重新定义HTTPException及RequestValidationError

本文共有1455个字,关键词:FastAPI

问题:FastAPI的HTTPException中有detail,如何去?

解决:重新定义HTTPException,及验证用的RequestValidationError

方法:

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from routers import router

app = FastAPI()
async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
    return JSONResponse(
        status_code=exc.status_code,
        content=exc.detail)
# 定义接管RequestValidationError的方法
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
    request: Request, exc: RequestValidationError
    ) -> JSONResponse:
    message = ""
    for error in exc.errors():
        message += ".".join(error.get("loc")) + ":" + error.get("msg") + ";"

    return JSONResponse(
        status_code=422,
        content={
            'code': 422,
            'msg': message,
            'body': exc.body})

# 通过加入自定义的函数,可以替换默认的报错函数
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)

app.include_router(router)

注:

无论是否使用APIRouter,重新定义HTTPException的方法必须放在main.py主文件中

参考:

https://www.pythonf.cn/read/167562
版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。
添加新评论
暂无评论