1

I am getting an exception on an HTTP GET request (http.client.HTTPConnection.getresponse), but so far have been unable to determine the nature of the exception (my Python is fairly rudimentary). The code looks like this:

try:
    r = conn.getresponse()
except Exception as x:
    logger.error('Error getting data:' + str(x))

This just results in logs looking like Error getting data:''. I could trap all the different types of exception that HTTPConnection.getresponse can raise, but that seems ridiculous given there are so many possible exception types and I'm just trying to debug how the connection is failing. Is there a way to inspect the exception object?

1
  • Show it’s type(x) or for a full trace, pass exc_info=True into that log statement Commented Jul 2, 2020 at 0:27

1 Answer 1

2

You almost certainly want to use logger.exception if you're using Python's standard library logger which adds more info about the exception (including a call stack).

From the docs:

Logger.exception() creates a log message similar to Logger.error(). The difference is that Logger.exception() dumps a stack trace along with it. Call this method only from an exception handler.

If you want to specifically format the type of the exception in your log message, do:

try:
    r = conn.getresponse()
except Exception as e:
    logger.error('%s: %s', type(e), e)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.