user1063287
user1063287

Reputation: 10879

Is it possible to conditionally handle multiple different AssertionError's and Exceptions?

Given this code block from a function in bottle-cork (link to code):

assert username, "Username must be provided."
assert password, "A password must be provided."
assert email_addr, "An email address must be provided."
if username in self._store.users:
    raise AAAException("User is already existing.")
if role not in self._store.roles:
    raise AAAException("Nonexistent role")
if self._store.roles[role] > max_level:
    raise AAAException("Unauthorized role")

I am wanting to handle the different assert 'errors' differently from an application, eg:

try:
    aaa.register(post_get('username'), post_get('password'), post_get('email_address'))
except AAAException as ae:
    #  do something
except AssertionError as aee:
    # do something else

The above works for conditional treatment of either a AAAException or AssertionError but is it possible to further refine that treatment based on the scenarios defined in the original code block ie (pseudo code):

try:
    aaa.register(post_get('username'), post_get('password'), post_get('email_address'))
except AAAException as ae:
    if AAAException == "User is already existing.":
            # do this
            # etc
except AssertionError as aee:
    if AssertionError == "Username must be provided.":
            # do this
            # etc

Upvotes: 1

Views: 57

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122135

Inside the except block

except AssertionError as aee:

the exception object instance thrown is aee; the class is AssertionError. You need to check the content of the instance:

except AssertionError as aee:
    if "Username must be provided." in aee.args:
        # do your thing

Upvotes: 2

Related Questions