fastapi: 第八章:使发生异常时返回json

一,fastapi在异常发生时默认不以json格式输出

看一段代码:

@router.get("/all")
def get_all_products():
    a = 0
    b = 100 / a
    print(b)
    products = [{"id": 1, "name": "手机"}, {"id": 2, "name": "电脑"}]
    return success(data=products)

被访问时的输出 

image

二,异常发生时的处理代码:

定义异常 

# app/core/exceptions.py
from fastapi import Request, FastAPI
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException

from app.utils.BaseResponse import BaseResponse

def register_exception_handlers(app: FastAPI):

    # 1. 捕获系统未知异常 (如: 代码崩溃、数据库连接断开 500)
    @app.exception_handler(Exception)
    async def all_exception_handler(request: Request, exc: Exception):
        # 注意:生产环境应将 exc 记录到日志系统(如 loguru)
        content = BaseResponse(code=500, msg="服务器内部错误,请稍后再试", data=None).model_dump()
        return JSONResponse(status_code=500, content=content)

添加到app对象上

# main.py
from fastapi import FastAPI
from app.api import products, users, account
from app.core.exceptions import register_exception_handlers

# 创建FastAPI应用
app = FastAPI(title="我的API项目")

# 注册全局异常捕获
register_exception_handlers(app)

三,测试效果

image

posted @ 2026-06-10 15:19  刘宏缔的架构森林  阅读(5)  评论(0)    收藏  举报