Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch exceptions that have specific error messages in Python?

When I have two Python exceptions that are the same exception class but a different error message, how do I catch them separately?

For specific use-case: I'm using the Facepy library to hit the Facebook Graph API. When the API returns an error that isn't Oauth related, Facepy raises a facepy.exceptions.FacebookError and passes the error message given by the Facebook API.

I'm consistently hitting two different errors that I'd like to treat differently and the only way to parse them is the error message, but I can't figure out how to write my except clause--here it is in pseudo-code:

try: 
    #api query

except facepy.exceptions.OAuthError and error_message = 'object does not exist':
    # do something

except facepy.exceptions.OAuthError and error_message = 'Hit API rate limit':
    # do something else

How do I write these except clauses to trigger off both the exception and the error message?

like image 855
Jeff Widman Avatar asked Sep 09 '26 15:09

Jeff Widman


1 Answers

Assuming the Exception's error message is in the error_message attribute (it may be something else — look at the Exception's __dict__ or source to find out):

try: 
    #api query

except facepy.exceptions.OAuthError as e:
    if e.error_message == "object does not exist":
        print "Do X"
    elif e.error_message == "Hit API rate limit":
        print "Do Y"
    else:
        raise
like image 176
Thomas Orozco Avatar answered Sep 12 '26 03:09

Thomas Orozco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!