Thursday, July 11, 2013

try-except HTTPError and URLError

urllib2's HTTPError subclasses URLError, so the bit of code below would never get to the second except statement, because that error would aready be caught in the first except. To get this code to work, reverse the order.

                response = urlopen(url)
            except URLError:
                # This happens if the server can't be reached.
                # Most likely the service is down, in this case we don't want
                # to do anything.
                # Another possibility is that we have the API url wrong.
                return True
            except HTTPError:
                # as Flattr API does return an error code (404 not found) when
                # looking for users that do not exist, urllib2 treats that as
                # an error, so no need to investigate or differentiate between
                # that and a normal HTTP error. Both are enough to not validate
                # a Flattr user.
                return False

No comments: