Frage

Suppose that I have http server located at (host:port) and I'm trying to use HTTPClient example from the tornado docs to fetch some data from that server, so I have a code below

from tornado import httpclient

http_client = httpclient.HTTPClient()
try:
    response = http_client.fetch("http://host:port", connect_timeout=2)
    print response.body

except httpclient.HTTPError as e:
    print e.code
    print e.message

http_client.close()

This works fine and in case everything goes well (host is available, server is working, etc.) my client successfully receives data from the server. Now I want to handle errors that can occur during connection process and handle them depending on the error code. I'm trying to get error code by using e.code in my exception handler, but it contains HTTP error codes only and I need some lower level error codes, for instance:

1) If server is not avaliable on the destination host and port it prints out

599
HTTP 599: [Errno 111] Connection refused

2) If it is impossible to reach the host (for example due to network connectivity problems), I receive the same HTTP 599 error code:

599
HTTP 599: [Errno 101] Connection refused

So I need to get Errno in my exception handler that would indicate actual lower level socket error and the only solution I see for now is to grep it from the text message I receive (e.message) but this solution looks rough and ugly.

War es hilfreich?

Lösung

I think your only option is to pull it out of e.message:

import re
m = re.search( "\[Errno (\d+)\]", e.message)
if m:
    errno = m.group(1)

On my platform (Linux), I actually get a socket.gaierror exception when I take your code example and use a bogus URL, which provides direct access to errno. But if you're dealing with tornado.httpclient.HTTPError, I don't think there's any way for you to get at it directly.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top