Skip to content

Instantly share code, notes, and snippets.

@jsenin
Created December 2, 2021 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsenin/cfddcc88753b6c6fe1af1bd4caed1df7 to your computer and use it in GitHub Desktop.
Save jsenin/cfddcc88753b6c6fe1af1bd4caed1df7 to your computer and use it in GitHub Desktop.
A proposal about exception subclassing
#---- 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