我需要使用urllib2.Request / urlopen来处理哪些错误/exception?

我有以下代码做回发到远程URL:

request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' }) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: checksLogger.error('HTTPError = ' + str(e.code)) except urllib2.URLError, e: checksLogger.error('URLError = ' + str(e.reason)) except httplib.HTTPException, e: checksLogger.error('HTTPException') 

postBackData是使用使用urllib.urlencode编码的字典创build的。 checksLogger是使用日志logging的logging器。

当远程服务器closures并且代码退出时(这是在客户服务器上,所以我不知道此时退出堆栈转储/错误是什么),此代码在运行时遇到了问题。 我假设这是因为有一个exception和/或错误没有被处理。 那么是否还有其他可能会触发的exception,我不能在上面处理?

添加genericsexception处理程序

 request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' }) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: checksLogger.error('HTTPError = ' + str(e.code)) except urllib2.URLError, e: checksLogger.error('URLError = ' + str(e.reason)) except httplib.HTTPException, e: checksLogger.error('HTTPException') except Exception: import traceback checksLogger.error('generic exception: ' + traceback.format_exc()) 

从文档页 urlopen条目,它看起来像你只需要赶上URLError 。 如果你真的想对冲你在urllib代码中的问题,你也可以把Exception作为一个退步。 只是except: ,因为这将捕获SystemExitKeyboardInterrupt也。

编辑:我的意思是说,你正在捕捉它应该抛出的错误。 如果抛出别的东西,这可能是由于urllib代码没有捕获到它应该捕获并包装在URLError 。 即使stdlib往往会错过像AttributeError这样简单的事情。 捕捉Exception作为后退(并logging它捕获的内容)将帮助您弄清楚发生了什么,而不会陷入SystemExitKeyboardInterrupt

 $ grep "raise" /usr/lib64/python/urllib2.py IOError); for HTTP errors, raises an HTTPError, which can also be raise AttributeError, attr raise ValueError, "unknown url type: %s" % self.__original # XXX raise an exception if no one else should try to handle raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) perform the redirect. Otherwise, raise HTTPError if no-one raise HTTPError(req.get_full_url(), code, msg, headers, fp) raise HTTPError(req.get_full_url(), code, raise HTTPError(req.get_full_url(), 401, "digest auth failed", raise ValueError("AbstractDigestAuthHandler doesn't know " raise URLError('no host given') raise URLError('no host given') raise URLError(err) raise URLError('unknown url type: %s' % type) raise URLError('file not on local host') raise IOError, ('ftp error', 'no host given') raise URLError(msg) raise IOError, ('ftp error', msg), sys.exc_info()[2] raise GopherError('no host given') 

在urllib2依赖项中也有可能出现exception,或者由于真正的错误而导致exception。

您最好通过自定义sys.excepthook将所有未捕获的exceptionlogging到文件中。 这里主要的经验法则就是永远不要纠正你不打算纠正的例外情况logging不是一种修正 所以不要抓住他们来logging他们。

您可以捕获所有exception并logging被捕获的内容:

  import sys import traceback def formatExceptionInfo(maxTBlevel=5): cla, exc, trbk = sys.exc_info() excName = cla.__name__ try: excArgs = exc.__dict__["args"] except KeyError: excArgs = "<no args>" excTb = traceback.format_tb(trbk, maxTBlevel) return (excName, excArgs, excTb) try: x = x + 1 except: print formatExceptionInfo() 

(代码来自http://www.linuxjournal.com/article/5821

另请阅读有关sys.exc_info的文档 。

我抓住了:

httplib.HTTPException
urllib2.HTTPError
urllib2.URLError

我相信这涵盖了一切,包括套接字错误。