I am working on a Project where I want to raise a error and I have been creating class each time I need a new Exception. I am staying away from generic / builtin errors as they are less descriptive for the purpose I need them for.
I came up with a solution but I am not sure if it is a pythonic way to create an instance.
def CustomError(name: str, message: str):
def constructor(self, msg=message):
self.message = msg
return
def repr_method(self):
return self.message
error = type(name,
(Exception, object),
{'__init__': constructor,
'__str__': repr_method})
return error(msg=message)
This does the trick as I can raise this error with a custom name and message instead of creating a new class every time. Please can someone let me know if this actually is a pythonic way if not then what is the recommended way?
I am expecting someone to confirm that this is actually a valid way of using higher order functions for creating a class instance or point me to a recommended way of doing it.