处理 urllib2.URLError 时获取 URL
这特别适用于 urllib2,但更普遍地适用于自定义异常处理。如何通过引发的异常将附加信息传递给另一个模块中的调用函数?我假设我会使用自定义异常类重新引发,但我不确定技术细节。
我不会用我尝试过但失败的内容来污染示例代码,而是将其简单地呈现为一块空白的石板。我的最终目标是让示例中的最后一行正常工作。
#mymod.py
import urllib2
def openurl():
req = urllib2.Request("http://duznotexist.com/")
response = urllib2.urlopen(req)
#main.py
import urllib2
import mymod
try:
mymod.openurl()
except urllib2.URLError as e:
#how do I do this?
print "Website (%s) could not be reached due to %s" % (e.url, e.reason)
This pertains to urllib2 specifically, but custom exception handling more generally. How do I pass additional information to a calling function in another module via a raised exception? I'm assuming I would re-raise using a custom exception class, but I'm not sure of the technical details.
Rather than pollute the sample code with what I've tried and failed, I'll simply present it as a mostly blank slate. My end goal is for the last line in the sample to work.
#mymod.py
import urllib2
def openurl():
req = urllib2.Request("http://duznotexist.com/")
response = urllib2.urlopen(req)
#main.py
import urllib2
import mymod
try:
mymod.openurl()
except urllib2.URLError as e:
#how do I do this?
print "Website (%s) could not be reached due to %s" % (e.url, e.reason)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以添加信息,然后重新引发异常。
You can add information to and then re-raise the exception.
我认为重新引发异常不是解决此问题的适当方法。
正如@Jonathan Vanasco 所说,
我的解决方案是覆盖
urllib2.HTTPRedirectHandler
的redirect_request
让我们尝试将 url 重定向到未知网址:
结果是:
I don't think re-raising the exception is an appropriate way to solve this problem.
As @Jonathan Vanasco said,
My solution is to overwrite
redirect_request
ofurllib2.HTTPRedirectHandler
let's try to redirect the url to an unknown url:
And the result is: