You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI:如何为特定路由自定义422异常?

为FastAPI单个路由替换422验证异常为自定义响应

核心方案:路由级异常处理器

FastAPI的api_route底层装饰器支持为单个路由指定专属异常处理器,可精准替换目标路由的422异常响应,不影响全局配置。

1. 导入必要模块

补充原有代码的依赖导入:

from fastapi import APIRouter, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel

2. 编写自定义异常处理器

定义处理422异常的函数,返回自定义格式的响应:

async def custom_validation_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,  # 可自定义状态码,无需局限于422
        content={
            "code": "PARAM_VALIDATION_FAILED",
            "message": "请求参数格式不符合要求,请检查后重试",
            "error_details": exc.errors()  # 可选保留原始错误详情,也可完全自定义
        }
    )

3. 修改目标路由装饰器

将原@router.post替换为@router.api_route,指定请求方法并绑定异常处理器:

router = APIRouter()

class PayloadSchema(BaseModel):
    value_int: int
    value_str: str

@router.api_route('/custom', methods=["POST"], exception_handlers={RequestValidationError: custom_validation_handler})
async def custom_route(payload: PayloadSchema):
    return payload

原理说明

  • api_route是FastAPI路由的底层实现,支持通过exception_handlers参数为当前路由设置独立的异常处理规则,优先级高于全局异常处理器。
  • 当该路由触发RequestValidationError(即默认的422异常)时,会自动调用你定义的处理器返回自定义响应,项目中其他路由仍沿用原有异常逻辑。

进阶:使用自定义异常类

若需要统一管理自定义异常,可先定义异常类再转换处理:

# 定义自定义异常
class CustomValidationError(Exception):
    def __init__(self, message: str, details: list):
        self.message = message
        self.details = details

# 自定义异常的响应处理器
async def custom_exception_handler(request: Request, exc: CustomValidationError):
    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,
        content={
            "code": "CUSTOM_VALID_ERR",
            "message": exc.message,
            "details": exc.details
        }
    )

# 将默认422异常转换为自定义异常
async def validation_error_converter(request: Request, exc: RequestValidationError):
    raise CustomValidationError("请求参数验证未通过", exc.errors())

# 绑定两个处理器到目标路由
@router.api_route('/custom', methods=["POST"], exception_handlers={
    RequestValidationError: validation_error_converter,
    CustomValidationError: custom_exception_handler
})
async def custom_route(payload: PayloadSchema):
    return payload

内容的提问来源于stack exchange,提问作者Octoloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 19:00:14