try:
response = urllib2.urlopen(request)
except urllib2.URLError as e:
response = json.loads(e.read())
return error(e.code(),response['errors'][0]['message'])
response = json.loads(response.read())
if 'errors' in response:
return error(response['ErrorCode'],response['Error'])
Here is the piece of code I am working with and you can help me out referring to this piece.
e
is the caught exception, here an instance of the urllib2.URLError
class or a subclass thereof. The code expects that instance to define the e.read()
and e.code()
methods.
However, it has some errors. It actually assumes it is catching the urllib2.HTTPError
exception, a subclass of URLError
. The exception handler certainly will catch such exceptions, but it could also be the base URLError
, in which case there won't be an e.read()
method! It also tries to call HTTPError.code
, which is not a method but an attribute.
The HTTPError
exception is thrown for HTTP error codes, so only when there was a response from the server. e.read()
lets you read the response body from the socket, and e.code
is the HTTP code the server responded with. From the documentation:
Though being an exception (a subclass of
URLError
), anHTTPError
can also function as a non-exceptional file-like return value (the same thing thaturlopen()
returns). This is useful when handling exotic HTTP errors, such as requests for authentication.
For the code to work in all cases, it would have to be corrected to:
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError as e:
response = json.loads(e.read())
return error(e.code, response['errors'][0]['message'])
perhaps with an additional except urllib2.URLError as e:
block to handle errors that don't involve a HTTP response.