我正在为python制作一个opensource twitch.tv API包装器,到目前为止我已经:
import urllib2
import json
import time
waittime = 1
baseurl = 'https://api.twitch.tv/kraken/'
class twitchchannelinfo():
def __init__ (self,channel):
self.channel = channel
time.sleep(waittime)
self.dict1 = json.loads(urllib2.urlopen(baseurl + 'channels/' + channel).read())
def getstatus(self):
return self.dict1 ['status']
def getdisplay_name(self):
return self.dict1 ['display_name']
def getmature(self):
return self.dict1 ['mature']
def getchanurl(self):
return self.dict1 ['url']
def getcreated_at(self):
return self.dict1 ['created_at']
def getteams(self):
return self.dict1 ['teams']
def getgame(self):
return self.dict1 ['game']
def getupdated_at(self):
return self.dict1 ['updated_at']
我想在此API中添加错误检查。服务器将返回一个类似于此的json响应,以显示错误:
{
"error": "Unprocessable Entity",
"status": 422,
"message": "Channel 'deeman' is not available on Twitch"
}
然后我使用json.loads
转换为字典。我如何检查这个词典的值“错误”还是有更好的方法呢?
答案 0 :(得分:2)
我建议这样做:
if 'error' in self.dict1:
raise ValueError("%s: %s" % (self.dict1["error"], self.dict1["message"]))
答案 1 :(得分:0)
if 'error' in self.dict1:
# do blah
答案 2 :(得分:0)
try:
self.dict1[u'error']
except KeyError:
## Do something here
这只是另一种使用try ...的方法,除了