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

调用raise_for_status后如何在except块获取原始响应体?

解决方法:保留raise_for_status,获取完整错误响应体

完全不用弃用raise_for_status(),因为requests.exceptions.HTTPError实例自带response属性,这个属性就是触发错误的原始响应对象,通过它就能拿到外部API返回的完整错误体。

具体修改后的代码如下:

try:
    resp = requests.post(
        url,
        json={...},
    )
    resp.raise_for_status()
    resp_result = resp.json()

except requests.exceptions.HTTPError as e:
    # 从错误对象中获取触发错误的原始响应
    error_resp = e.response
    try:
        # 尝试解析响应体的JSON内容
        resp_result = error_resp.json()
    except ValueError:
        # 兼容外部API返回非JSON格式错误的情况
        resp_result = {"error": f"{str(e)} | 错误响应内容: {error_resp.text}"}

return JSONResponse(resp_result)

关键说明:

  • e.response直接指向触发HTTP错误的响应对象,和requests.post返回的resp是同一个实例,因此可以调用json()或text方法获取完整响应内容。
  • 额外增加的try-except ValueError是为了避免外部API返回非JSON格式错误时,解析失败导致二次报错,保证代码的健壮性。

修改后,当外部API返回400错误时,你的服务端点就能直接返回外部API的完整错误JSON结构,比如:

{
    "error": {
        "message": "API key invalid",
        "type": "invalid_request_error",
        "param": null,
        "code": null
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:00:59