python data_error ai_generated true

值错误:路径参数'id'的值无效:期望整数,得到'abc'。

ValueError: Invalid value for path parameter 'id': expected int, got 'abc'

ID: python/starlette-route-parameter-type

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2026-05-20首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

路径参数类型转换失败,例如期望整数但提供了字符串。

English

路径参数类型转换失败,例如期望整数但提供了字符串。

generic

解决方案

  1. 95% 成功率
    使用类型转换装饰器:
    @app.route("/items/{id}")
    async def get_item(request, id: int):
        return {"id": id}
  2. 90% 成功率
    手动转换并处理错误:
    try:
        id = int(request.path_params['id'])
    except ValueError:
        return JSONResponse(status_code=400, content={"error": "Invalid id"})

无效尝试

常见但无效的做法:

  1. 80% 失败

    尝试使用int()强制转换但未捕获异常。

  2. 70% 失败

    忽略错误,导致路由匹配失败。