我有一个 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
具有 request
和 response
属性:
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/