使用额外信息重新引发 HTTPError
如果是 404,我想捕获带有额外信息的 urllib2.HTTPError:
try:
data = urlopen(url)
except HTTPError, e: # Python 2.5 syntax
if e.code == 404:
raise HTTPError('data not found on remote')
else:
raise
但这不起作用,因为 HTTPError 的 init 需要多个未记录的参数。如果它确实起作用,它将丢失回溯和原始消息。我也尝试过
if e.code == 404:
e.message = 'data not found on remote: %s' % e.message
raise
,但这只是重新引发了异常,而没有额外的信息。我应该怎么办?
I want to catch a urllib2.HTTPError
with extra information if it's a 404:
try:
data = urlopen(url)
except HTTPError, e: # Python 2.5 syntax
if e.code == 404:
raise HTTPError('data not found on remote')
else:
raise
but this doesn't work because HTTPError
's init takes multiple arguments, which are undocumented. It it did work, it would lose the backtrace and the original message. I also tried
if e.code == 404:
e.message = 'data not found on remote: %s' % e.message
raise
but that just re-raised the exception without extra information. What should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HTTPError 已经包含您需要的所有信息,您可以像这样简单地重新引发它
The HTTPError already contains all the information you require, you can simply reraise it like this
您只需要使用
e.msg
而不是e.message
。脚本:prints
您当然可以使用封闭的 try/ except: 来整理它:
它简单地打印
异常具有所有原始细节:
e.__dict__
看起来像You just need to use
e.msg
rather thane.message
. The script:prints
You can of course tidy this up with an enclosing try/except:
which prints simply
The exception has all of the original detail:
e.__dict__
looks like