在调用raise_for_status()后,如何在except块中获得原始有效载荷体



我有一个调用外部API的python web服务器端点

try:
resp = requests.post(
url,
json={...},
)
resp.raise_for_status()
resp_result = resp.json()
except requests.exceptions.HTTPError as e:
print(e)
err_msg = str(e)
resp_result = {"error": err_msg}
return JSONResponse(resp_result)

问题是,当我调用的API返回400时,它按预期进入except块,但返回的错误消息并不是外部API返回的完整错误消息。

当外部API失败时,它返回一个400,其正文如下

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

但是当我做print(e)时,我得到的是

400 Client Error: Bad Request for url: https://X

但是我想在这里将完整的外部API错误消息返回给端点的调用者。如何在except块中获得完整的错误体?如果我想这样做,我需要不使用raise_for_status吗?

EDIT:正如Rasen58所评论的那样,一旦try块失败并且执行except块,响应将超出范围。这意味着您将无法访问except块中的api错误消息。你能做的就是检查状态码,如果是400就返回错误:

try:
resp = requests.post(
url,
json={...},
)
if resp.status_code in [400, 404]: 
# handle it accordingly, e.g. print the API response: 
print(resp.json())
return
resp.raise_for_status()
resp_result = resp.json()

except Exception as e:
# handle the exception

最新更新