Requests is a great python
lib to handle http calls, it is simple and intuitive to use. But when
actually implement your class, to handle exceptions raised by Requests,
the official document seems to be a little slim on it. First, unlike
urllib2, Requests does not treat http errors as exceptions (it has a
status_code to reflect the error, but won’t actually raise the
exception flag). So I implement a customized error class, combined with
a if condition statement, I manage to catch the http error as an
exception.
Python code
c() is the child function that actually takes care of the requests
calling. If in the response dictionary, there is a ‘code’ key, (or you
could use r.status_code != 200), that means there is a http error, and
we could raise our customized error class to pass alone the error
information to the mother function (or class), in our case, the function
d().
and in d()’s exception handling, you could deal with different
situations by implement if condition statement, in the example code, I
just print out the message for demo purpose.
Hope this helps, enjoy :)
Comments
comments powered by Disqus