我正在使用 urllib 调用 API。当某些事情不符合预期时,API 会向用户抛出错误(例如 HTTP Error 415: Unsupported Media Type)。但除此之外,API 会返回一个包含更多信息的 JSON。我想将该 json 传递给异常并在那里解析它,这样我就可以向用户提供有关错误的信息。
这可能吗?如果是,它是如何完成的?
额外信息:
错误:HTTPError
--编辑--
根据要求,这里有一些代码(我想在异常中阅读 resp):
def _sendpost(url, data=None, filetype=None):
try:
global _auth
req = urllib.request.Request(url, data)
req.add_header('User-Agent', _useragent)
req.add_header('Authorization', 'Bearer ' + _auth['access_token'])
if filetype is not None:
req.add_header('Content-Type', filetype)
resp = urllib.request.urlopen(req, data)
data = json.loads(resp.read().decode('utf-8'), object_pairs_hook=OrderedDict)
except urllib.error.HTTPError as e:
print(e)
return data
--编辑2-- 我不想使用额外的库/模块。因为我不控制目标机器。
请您参考如下方法:
代码
import urllib.request
import urllib.error
try:
request = urllib.request.urlopen('https://api.gutefrage.net')
response = urllib.urlopen(request)
except urllib.error.HTTPError as e:
error_message = e.read()
print(error_message)
输出
b'{"error":{"message":"X-Api-Key header is missing or invalid","type":"API_REQUEST_FORBIDDEN"}}'
没有询问但是使用模块 json 你可以通过 将它转换为 dict
import json
json.loads(error_message.decode("utf-8"))
从字节串中得到字典。
