1

I am trying to create the following exception and call it in another function:

### The exception
class GoogleAuthError(Exception):
    def __init__(self, message, code=403):
        self.code = code
        self.message = message

### Generating the exception
raise GoogleAuthError(message="There was an error authenticating")

### printing the exception
try:
    do_something()
except GoogleAuthError as e:
    print(e.message)

Basically, I want it to print "There was an error authenticating". How would I do this properly, or is the above the correct way to do it?

1 Answer 1

3

Remove the code argument from your __init__. You aren't using it.

You can also delegate the handling of the error message to the parent Exception class, which already knows about messages

class GoogleAuthError(Exception):
    def __init__(self, message):
        super().__init__(message)
        self.code = 403

try:
    raise GoogleAuthError('There was an error authenticating')
except GoogleAuthError as e:
    print(e)

# There was an error authenticating 
Sign up to request clarification or add additional context in comments.

5 Comments

Also worth mentioning: exception message attribute has been deprecated since the dinosaurs roamed the earth. Only *args are considered.
@wim Not sure how that is relevant, since the OP defined their own message attribute. That one certainly isn't deprecated.
@Aran-Fey It's relevant because this code doesn't (and shouldn't) assign a message attribute on the exception instance, which is something that deviates from the OP's original API ... I think that's worth mentioning, don't you?
@wim Not sure. How could assigning something to message cause a problem? Unless it used to be a read-only attribute, I don't see what could go wrong.
If the OP has a bunch of code which is printing or logging an err.message (similar as shown in the question), they will need to modify that code because there is no longer a message attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.