Created
December 2, 2021 06:49
-
-
Save jsenin/cfddcc88753b6c6fe1af1bd4caed1df7 to your computer and use it in GitHub Desktop.
A proposal about exception subclassing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#---- current behaviour | |
# class UsernameTooShortError(Exception): | |
# MSG = 'Username too short' | |
# pass | |
# def add_user(username=None): | |
# if len(username) < 4: | |
# raise UsernameTooShortError() | |
# try: | |
# username = 'ted' | |
# print ("Adding a user", username) | |
# add_user(username=username) | |
# except UsernameTooShortError as exc: | |
# print("Error", exc.MSG) | |
# recomended exception message using str() | |
# we loose the message | |
# except UsernameTooShortError as exc: | |
# print("Error", str(exc)) | |
# proposal | |
# class UsernameTooShortError(Exception): | |
# MSG = 'Username too short' | |
# def __str__(self): | |
# return str(self.MSG) | |
# def add_user(username=None): | |
# if len(username) < 4: | |
# raise UsernameTooShortError() | |
# try: | |
# username = 'ted' | |
# print ("Adding a user", username) | |
# add_user(username=username) | |
# except UsernameTooShortError as exc: | |
# print("Error", str(exc)) | |
# abstraction | |
class BaseError(Exception): | |
def __init__(self, message=None, *args, **kwargs): | |
self.message = message | |
def __str__(self): | |
default = self.__class__.__name__ | |
if hasattr(self, 'MSG'): | |
default = getattr(self, 'MSG') | |
message = self.message or default | |
return str(message) | |
class UsernameTooShortError(BaseError): | |
pass | |
#MSG = 'Username too short' | |
def add_user(username=None): | |
if len(username) < 4: | |
#raise UsernameTooShortError(f"Username {username} it's too short") | |
raise UsernameTooShortError() | |
try: | |
username = 'ted' | |
print ("Adding a user", username) | |
add_user(username=username) | |
except UsernameTooShortError as exc: | |
print("Error", str(exc)) | |
#print("Error", str(exc.MSG)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment