Python3如何捕获链式异常

时间:2018-04-27 13:55:34

标签: python-3.x elasticsearch error-handling

我使用Elasticsearch python API设计一个用户友好的应用程序,将解析后的结果放到elasticsearch服务器上。

我遇到的问题是,当我使用有效的url作为主机启动elasticsearch对象,而不是实际的elasticsearch主机地址时,我得到链式异常,如下所示:

Traceback (most recent call last):
  File "/local/data/PYTHONLIB/lib/python3.5/site 
    packages/urllib3/connection.py", line 141, in _new_conn
    (self.host, self.port), self.timeout, **extra_kw)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/util/connection.py", line 83, in create_connection
    raise err
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/util/connection.py", line 73, in create_connection
    sock.connect(sa)
OSError: [Errno 101] Network is unreachable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/elasticsearch/connection/http_urllib3.py", line 166, in 
    perform_request
    response = self.pool.urlopen(method, url, body, retries=False, 
    headers=request_headers, **kw)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connectionpool.py", line 639, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/util/retry.py", line 333, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/packages/six.py", line 686, in reraise
    raise value
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connectionpool.py", line 357, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/usr/lib/python3.5/http/client.py", line 1106, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python3.5/http/client.py", line 1151, in _send_request
    self.endheaders(body)
  File "/usr/lib/python3.5/http/client.py", line 1102, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python3.5/http/client.py", line 934, in _send_output
    self.send(msg)
  File "/usr/lib/python3.5/http/client.py", line 877, in send
    self.connect()
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connection.py", line 166, in connect
    conn = self._new_conn()
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connection.py", line 150, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: 
<urllib3.connection.HTTPConnection object at 0x7fc714997828>: Failed 
to establish a new connection: [Errno 101] Network is unreachable
GET http://google.ca:9200/_nodes/_all/http [status:N/A 
request:10.046s]
Traceback (most recent call last):
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connection.py", line 141, in _new_conn
    (self.host, self.port), self.timeout, **extra_kw)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/util/connection.py", line 83, in 
    create_connection
    raise err
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/util/connection.py", line 73, in create_connection
    sock.connect(sa)
OSError: [Errno 101] Network is unreachable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/elasticsearch/connection/http_urllib3.py", line 166, in 
    perform_request
    response = self.pool.urlopen(method, url, body, retries=False, 
    headers=request_headers, **kw)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connectionpool.py", line 639, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/util/retry.py", line 333, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/packages/six.py", line 686, in reraise
    raise value
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connectionpool.py", line 357, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/usr/lib/python3.5/http/client.py", line 1106, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python3.5/http/client.py", line 1151, in 
    _send_request
    self.endheaders(body)
  File "/usr/lib/python3.5/http/client.py", line 1102, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python3.5/http/client.py", line 934, in _send_output
    self.send(msg)
  File "/usr/lib/python3.5/http/client.py", line 877, in send
    self.connect()
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connection.py", line 166, in connect
    conn = self._new_conn()
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/urllib3/connection.py", line 150, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: 
<urllib3.connection.HTTPConnection object at 0x7fc714997a20>: Failed 
to establish a new connection: [Errno 101] Network is unreachable
Traceback (most recent call last):
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/elasticsearch/client/__init__.py", line 188, in __init__
    self.transport = transport_class(_normalize_hosts(hosts), **kwargs)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/elasticsearch/transport.py", line 122, in __init__
    self.sniff_hosts(True)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/elasticsearch/transport.py", line 235, in sniff_hosts
    node_info = self._get_sniff_data(initial)
  File "/local/data/PYTHONLIB/lib/python3.5/site-
    packages/elasticsearch/transport.py", line 204, in _get_sniff_data
    raise TransportError("N/A", "Unable to sniff hosts.")
elasticsearch.exceptions.TransportError: TransportError(N/A, 'Unable 
 to sniff hosts.')

我希望捕获所有异常并生成更加用户友好的错误消息,例如:&#34;主机无效,连接错误!&#34;

我试图在不泄露太多实施细节的情况下实现这一目标的是:

from urllib3.exceptions import NewConnectionError
from elasticsearch import TransportError


try:
    Elasticsearch(http,
                  sniff_on_start=True,
                  sniff_on_connection_fail=True,
                  sniffer_timeout=60
                  )
except (OSError, NewConnectionError, TransportError) as e:
    print("Invalid host, connection error!")
    raise SystemExit(1)

或:

from urllib3.exceptions import NewConnectionError
from elasticsearch import TransportError


try:
    Elasticsearch(http,
                  sniff_on_start=True,
                  sniff_on_connection_fail=True,
                  sniffer_timeout=60
                  )
except Exception as e:
    print("Invalid host, connection error!")
    raise SystemExit(1)

或:

from urllib3.exceptions import NewConnectionError
from elasticsearch import TransportError

try:
    try:
        try:
            Elasticsearch(http,
                          sniff_on_start=True,
                          sniff_on_connection_fail=True,
                          sniffer_timeout=60
                          )
        except NewConnectionError as e:
            print("Caught NewConnectionError")
    except OSError as e:
        print("Caught OSError")
except TransportError as e:
    print("Invalid host, connection error!")
    raise SystemExit(1)

但是每次试验,我只能捕获TransportError,它是elasticsearch API抛出的最后一个异常。 有没有办法让我在不改变源代码中抛出异常的方式之前实际捕获所有异常?

0 个答案:

没有答案