使用额外信息重新引发 HTTPError

发布于 2024-11-10 04:05:15 字数 460 浏览 3 评论 0原文

如果是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

满地尘埃落定 2024-11-17 04:05:15

HTTPError 已经包含您需要的所有信息,您可以像这样简单地重新引发它

raise HTTPError(e.url, e.code, "your message.", e.hdrs, e.fp)

The HTTPError already contains all the information you require, you can simply reraise it like this

raise HTTPError(e.url, e.code, "your message.", e.hdrs, e.fp)
郁金香雨 2024-11-17 04:05:15

您只需要使用 e.msg 而不是 e.message。脚本:

from urllib2 import urlopen, HTTPError

url = 'http://www.red-dove.com/frob'

try:
    data = urlopen(url)
except HTTPError, e:  # Python 2.5 syntax
    if e.code == 404:
        e.msg = 'data not found on remote: %s' % e.msg
    raise

prints

Traceback (most recent call last):
  File "c:\temp\test404.py", line 6, in <module>
    data = urlopen(url)
  File "C:\Python\Lib\urllib2.py", line 124, in urlopen
    return _opener.open(url, data)
  File "C:\Python\Lib\urllib2.py", line 387, in open
    response = meth(req, response)
  File "C:\Python\Lib\urllib2.py", line 498, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python\Lib\urllib2.py", line 425, in error
    return self._call_chain(*args)
  File "C:\Python\Lib\urllib2.py", line 360, in _call_chain
    result = func(*args)
  File "C:\Python\Lib\urllib2.py", line 506, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: data not found on remote: Not Found

您当然可以使用封闭的 try/ except: 来整理它:

from urllib2 import urlopen, HTTPError

url = 'http://www.red-dove.com/frob'

try:
    try:
        data = urlopen(url)
    except HTTPError, e:  # Python 2.5 syntax
        if e.code == 404:
            e.msg = 'data not found on remote: %s' % e.msg
        raise
except HTTPError, e:
    print e

它简单地打印

HTTP Error 404: data not found on remote: Not Found

异常具有所有原始细节: e.__dict__ 看起来像

{'__iter__': <bound method _fileobject.__iter__ of <socket._fileobject object at   0x00AF2EF0>>,
 'code': 404,
 'fileno': <bound method _fileobject.fileno of <socket._fileobject object at 0x00AF2EF0>>,
 'fp': <addinfourl at 12003088 whose fp = <socket._fileobject object at 0x00AF2EF0>>,
 'hdrs': <httplib.HTTPMessage instance at 0x00B727B0>,
 'headers': <httplib.HTTPMessage instance at 0x00B727B0>,
 'msg': 'data not found on remote: Not Found',
 'next': <bound method _fileobject.next of <socket._fileobject object at 0x00AF2EF0>>,
 'read': <bound method _fileobject.read of <socket._fileobject object at 0x00AF2EF0>>,
 'readline': <bound method _fileobject.readline of <socket._fileobject object at 0x00AF2EF0>>,
 'readlines': <bound method _fileobject.readlines of <socket._fileobject object at 0x00AF2EF0>>,
 'url': 'http://www.red-dove.com/frob'}

You just need to use e.msg rather than e.message. The script:

from urllib2 import urlopen, HTTPError

url = 'http://www.red-dove.com/frob'

try:
    data = urlopen(url)
except HTTPError, e:  # Python 2.5 syntax
    if e.code == 404:
        e.msg = 'data not found on remote: %s' % e.msg
    raise

prints

Traceback (most recent call last):
  File "c:\temp\test404.py", line 6, in <module>
    data = urlopen(url)
  File "C:\Python\Lib\urllib2.py", line 124, in urlopen
    return _opener.open(url, data)
  File "C:\Python\Lib\urllib2.py", line 387, in open
    response = meth(req, response)
  File "C:\Python\Lib\urllib2.py", line 498, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python\Lib\urllib2.py", line 425, in error
    return self._call_chain(*args)
  File "C:\Python\Lib\urllib2.py", line 360, in _call_chain
    result = func(*args)
  File "C:\Python\Lib\urllib2.py", line 506, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: data not found on remote: Not Found

You can of course tidy this up with an enclosing try/except:

from urllib2 import urlopen, HTTPError

url = 'http://www.red-dove.com/frob'

try:
    try:
        data = urlopen(url)
    except HTTPError, e:  # Python 2.5 syntax
        if e.code == 404:
            e.msg = 'data not found on remote: %s' % e.msg
        raise
except HTTPError, e:
    print e

which prints simply

HTTP Error 404: data not found on remote: Not Found

The exception has all of the original detail: e.__dict__ looks like

{'__iter__': <bound method _fileobject.__iter__ of <socket._fileobject object at   0x00AF2EF0>>,
 'code': 404,
 'fileno': <bound method _fileobject.fileno of <socket._fileobject object at 0x00AF2EF0>>,
 'fp': <addinfourl at 12003088 whose fp = <socket._fileobject object at 0x00AF2EF0>>,
 'hdrs': <httplib.HTTPMessage instance at 0x00B727B0>,
 'headers': <httplib.HTTPMessage instance at 0x00B727B0>,
 'msg': 'data not found on remote: Not Found',
 'next': <bound method _fileobject.next of <socket._fileobject object at 0x00AF2EF0>>,
 'read': <bound method _fileobject.read of <socket._fileobject object at 0x00AF2EF0>>,
 'readline': <bound method _fileobject.readline of <socket._fileobject object at 0x00AF2EF0>>,
 'readlines': <bound method _fileobject.readlines of <socket._fileobject object at 0x00AF2EF0>>,
 'url': 'http://www.red-dove.com/frob'}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文