简体   繁体   中英

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?

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

facepy 's OAuthError derives from FacebookError and that has message attribute. https://github.com/jgorset/facepy/blob/master/facepy/exceptions.py#L8 . So, you can use if condition with the message like this

try:
    #api query
except facepy.exceptions.OAuthError as error:
    if 'object does not exist' == error.message:
       # do something
    elif 'Hit API rate limit' == error.message:
       # do something else
    else:
       raise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM