更好的是,优雅地处理 3rd-party api 问题的最佳方法是什么?
什么意思 API 已关闭,API 返回 http 404 , 500 ...
或者您的意思是当 API 无法访问时?
首先,我认为您无法在尝试访问之前知道一般 Web 服务是否已关闭,所以我会推荐第一个您可以这样做:
import httplib
conn = httplib.HTTPConnection('www.google.com') # I used here HTTP not HTTPS for simplify
conn.request('HEAD', '/') # Just send a HTTP HEAD request
res = conn.getresponse()
if res.status == 200:
print "ok"
else:
print "problem : the query returned %s because %s" % (res.status, res.reason)
并且为了检查 API 是否无法访问,我认为您最好尝试一下:
import httplib
import socket
try:
# I don't think you need the timeout unless you want to also calculate the response time ...
conn = httplib.HTTPSConnection('www.google.com')
conn.connect()
except (httplib.HTTPException, socket.error) as ex:
print "Error: %s" % ex
如果你想要更通用的东西,你可以混合这两种方式,希望这会有所帮助