gpt4 book ai didi

python - 当通过 raise_for_status 和 python-requests 引发 HTTPError 时如何包含响应

转载 作者:行者123 更新时间:2023-12-05 06:26:13 29 4
gpt4 key购买 nike

我有一个 API,可以在发生 4xx 错误时返回 json 消息。一个例子是 {'message': 'Could not decode JWT token'} .当我处理异常时,该消息丢失了。

class HttpService:
def __init__(self, url, token):
self.headers={"Authorization": token}
self.requests = Requests(url)

def get(self, path):
try:
response = self.requests.get(path, headers=self.headers)
response.raise_for_status()

return response.json()
except requests.exceptions.RequestException as e:
raise HttpServiceException(e)

class HttpServiceException(Exception):
pass

在另一个类中我有一个类似的方法

def get_user(self, user_id):
try:
return self.http_service.get("user/" + user_id)
except HttpServiceException as e:
print(e) // this prints "401 Client Error: Unauthorized for url: <url>"

我希望能够看到 {'message': 'Could not decode JWT token'}以及 401 Client Error: Unauthorized for url: <url>打印异常时的消息。实现该目标的最佳/最简单方法是什么?

谢谢。

最佳答案

RequestException 具有 requestresponse 属性:

import requests

try:
response = requests.get('https://httpbin.org/status/403')
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(e.request)
print(e.response)

关于python - 当通过 raise_for_status 和 python-requests 引发 HTTPError 时如何包含响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56419307/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com