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

如何自定义FastAPI中Header缺失HMAC的错误响应

自定义FastAPI中HMAC请求头缺失的错误响应

问题场景

我有一段FastAPI代码:

@app.post('/api_name')
async def api_func(HMAC: str = Header(...)):
    try:
        return 'success'
    except Exception as err:
        return err

当请求头未携带HMAC时,FastAPI会返回默认的422错误响应:

{
    "detail": [
        {
            "loc": [
                "header",
                "HMAC"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

我希望把这个错误响应改成自定义格式:

{
"Success": false,
"Error": "HMAC is required in Header"
}

尝试过在路由函数里捕获HTTPException,但无效,还是返回默认错误:

@app.post('/api_name')
async def api_func(HMAC: str = Header(...)):
    try:
        return 'success'

    except HTTPException as err:
        if err.status_code == 422 and 'HMAC' in err.detail[0]['loc']:
            return {'Success': False, 'Error': 'HMAC is required in Header'}
        else:
            raise err

解决方案

FastAPI的请求参数验证(包括Header)是在进入路由函数之前完成的,所以路由内部的try-except捕获不到这个422错误。需要用FastAPI的自定义异常处理器来处理RequestValidationError(422错误对应的异常类型)。

实现代码

from fastapi import FastAPI, Header, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse

app = FastAPI()

# 自定义异常处理器
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    # 遍历错误细节,匹配HMAC头缺失的情况
    for error in exc.errors():
        if error["loc"] == ["header", "HMAC"] and error["type"] == "value_error.missing":
            return JSONResponse(
                status_code=422,
                content={"Success": False, "Error": "HMAC is required in Header"}
            )
    # 其他验证错误返回默认响应
    return JSONResponse(
        status_code=422,
        content={"detail": exc.errors()}
    )

@app.post('/api_name')
async def api_func(HMAC: str = Header(...)):
    return 'success'

说明

  1. 注册RequestValidationError的异常处理器,拦截所有请求验证错误
  2. 在处理器中检查错误的位置(loc)和类型(type),精准匹配HMAC头缺失的场景
  3. 匹配成功则返回自定义格式响应,否则保留默认的验证错误输出
  4. 路由函数无需额外的try-except逻辑,验证错误已被处理器提前拦截

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:05:32