@chistya

Как правильно обработать исключение?

Добрый день.

Как правильно обработать исключение в python 3 и модуле elasticsearch при недоступности сервера?
Например:
...
es = Elasticsearch(elastic_servers, http_auth=(elastic_user, elastic_password))
res = es.search(index=indices, body=query)
...

и потом огромная простыня из traceback:
Traceback
GET 192.168.0.1:9200/index-*/_search [status:N/A request:0.004s]
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/urllib3/connection.py", line 141, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
File "/usr/lib/python3.6/site-packages/urllib3/util/connection.py", line 83, in create_connection
raise err
File "/usr/lib/python3.6/site-packages/urllib3/util/connection.py", line 73, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/elasticsearch/connection/http_urllib3.py", line 149, in perform_request
response = self.pool.urlopen(method, url, body, retries=False, headers=request_headers, **kw)
File "/usr/lib/python3.6/site-packages/urllib3/connectionpool.py", line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/lib/python3.6/site-packages/urllib3/util/retry.py", line 333, in increment
raise six.reraise(type(error), error, _stacktrace)
File "/usr/lib/python3.6/site-packages/urllib3/packages/six.py", line 686, in reraise
raise value
File "/usr/lib/python3.6/site-packages/urllib3/connectionpool.py", line 601, in urlopen
chunked=chunked)
File "/usr/lib/python3.6/site-packages/urllib3/connectionpool.py", line 357, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/lib64/python3.6/http/client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/lib64/python3.6/http/client.py", line 1285, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/lib64/python3.6/http/client.py", line 1234, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/lib64/python3.6/http/client.py", line 1026, in _send_output
self.send(msg)
File "/usr/lib64/python3.6/http/client.py", line 964, in send
self.connect()
File "/usr/lib/python3.6/site-packages/urllib3/connection.py", line 166, in connect
conn = self._new_conn()
File "/usr/lib/python3.6/site-packages/urllib3/connection.py", line 150, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: : Failed to establish a new connection: [Errno 111] Connection refused

...

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/tmp/test.py", line 56, in
res = es.search(index=indices, body=query.format(t_noisy_silents, t_duntil, t_dfrom))
File "/usr/lib/python3.6/site-packages/elasticsearch/client/utils.py", line 76, in _wrapped
return func(*args, params=params, **kwargs)
File "/usr/lib/python3.6/site-packages/elasticsearch/client/__init__.py", line 636, in search
doc_type, '_search'), params=params, body=body)
File "/usr/lib/python3.6/site-packages/elasticsearch/transport.py", line 314, in perform_request
status, headers_response, data = connection.perform_request(method, url, params, body, headers=headers, ignore=ignore, timeout=timeout)
File "/usr/lib/python3.6/site-packages/elasticsearch/connection/http_urllib3.py", line 158, in perform_request
raise ConnectionError('N/A', str(e), e)
elasticsearch.exceptions.ConnectionError: ConnectionError(: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(: Failed to establish a new connection: [Errno 111] Connection refused)

Плюс ConnectionRefusedError и urllib3.exceptions.NewConnectionError 4 раза в выводе присутствуют. Как это аккуратно обработать и вывести красивое сообщение о недоступности сервера?
  • Вопрос задан
  • 335 просмотров
Пригласить эксперта
Ответы на вопрос 2
@Stqs
senior software developer
chistya,

а чо try-except отменили уже?
Ответ написан
Комментировать
@bbkmzzzz
try:
    es = Elasticsearch(elastic_servers, http_auth=(elastic_user, elastic_password))
    res = es.search(index=indices, body=quer
except Exception as exc:
    print('ALARM!', exc.args)


если нужен стек исключения - модуль traceback поможет
from traceback import format_exc
...
try:
    es = Elasticsearch(elastic_servers, http_auth=(elastic_user, elastic_password))
    res = es.search(index=indices, body=quer
except:
    print('ALARM!')
    print(format_exc(10)) # 10 - глубина стека
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы