我们闲话少说,来看下面的一段代码:

import urllib2

url='http://httpbin.org/status/500'
try:
    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
    print(response.read())
except urllib2.HTTPError as e:
    print('HTTPError')
    print(response.read())

上面的代码的核心需求是在异常时把服务端返回的异常报文打印出来,以便后续的排障,当然我们也看到了在except后面的异常处理代码块里面的最后一行,也确实在尝试打印服务端返回的异常报文,但是呢如果不太有经验的小伙伴可能会遇到下面的报错,

 ✘  ~/Downloads  /usr/bin/python /Users/sharp/Downloads/test.py
HTTPError
Traceback (most recent call last):
  File "/Users/sharp/Downloads/test.py", line 10, in <module>
    print(response.read())
NameError: name 'response' is not defined

其实这样的处理方式在python3中是可以的,但是至于python2为什么不可以,不知道是受限于什么,下面我来说一下解决的办法,见如下代码:

import urllib2

url='http://httpbin.org/status/500'
try:
    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
    print(response.read())
except urllib2.HTTPError as e:
    print('HTTPError')
    # print(response.read())
    print(e.read())
    print(e.headers)

我们这时可以看到竟然可以在异常对象e的read()方法中去读取异常报文,同时我们也从异常对象e中把服务端返回的response header打印了出来,不得不说这种方式真是巧妙呀,下面是上面的代码返回的结果:

✘  ~/Downloads  /usr/bin/python /Users/sharp/Downloads/test.py
HTTPError

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Type: text/html; charset=utf-8
Date: Sun, 30 May 2021 03:42:32 GMT
Keep-Alive: timeout=4
Proxy-Connection: keep-alive
Server: gunicorn/19.9.0
Content-Length: 0
最后修改:2021 年 05 月 30 日 03 : 47 AM