What errors/exceptions do I need to handle with urllib2.Request / urlopen?

前端 未结 5 1817
别那么骄傲
别那么骄傲 2020-12-04 09:28

I have the following code to do a postback to a remote URL:

request = urllib2.Request(\'http://www.example.com\', postBackData, { \'User-Agent\' : \'My User          


        
5条回答
  •  Happy的楠姐
    2020-12-04 10:34

    Add generic exception handler:

    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())
    

提交回复
热议问题