David542
David542

Reputation: 110073

How to create a custom Exception with error message and status code in python3

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?

Upvotes: 1

Views: 1149

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60944

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 

Upvotes: 3

Related Questions