I’m writing a basic logging utility, and I want it to use a callback function, and then check for a list of exceptions that might have occurred.
I think the code will explain for itself.
I know the following example is not valid code, it is included for clarification.
def Except(self, func, exceptions, *args, **kwargs):
"""Used for logging exceptions"""
try:
func(*args, **kwargs)
for exception in exceptions: # Obviously this doesn't work.
except exception as e:
self.log(f"{e}", "error", 4)
However, I am surprised unpacking doesn’t work.
def Except(self, func, exceptions, *args, **kwargs):
"""Used for logging exceptions"""
try:
func(*args, **kwargs)
except (*exceptions) as e:
self.log(f"{e}", "error", 4)
Is there any way to dynamically catch exceptions with a callback function like this? I can’t seem to find anything in the docs about it.
>Solution :
You can create a custom Except class like this,
def Except(func, exceptions, *args, **kwargs):
try:
func(*args, **kwargs)
except exceptions as e:
print(f"{e}", "error")
def foo():
l = [1]
return l[1]
# Exception as tuple
exceptions = (TypeError, KeyError, IndexError)
Except(foo, exceptions)
Outputs:
list index out of range error