我有一个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>
消息。实现这一目标的最好/最简单的方法是什么?
谢谢。
发布于 2019-06-03 06:24:19
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)
https://stackoverflow.com/questions/56419307
复制相似问题