0

I would like to create a function that takes function as an argument and list of tuples. First element of a tuple will be an error and second one, a message. Example call:

handle_error(sum, [(ValueError, 'bad value'), (AttributeError, 'attribute error')]) 

This errors are meant to be handled in try/except blocks. I guess that it is not possible to dynamically define number of excepts. What is best practice to perform operation ilustrated as in the pseudocode example below?

def handle_error(function, errors): try: function() for error in errors: except error[0] as e: print(error[1]) 

I want to achieve such behaviour to make cleaner logging in my app.

0

1 Answer 1

1

Use dict as Exceptions are hashable.

from collections.abc import Callable # just for type hinting. def handle_error(callable_: Callable, error_dict: dict): try: callable_() except Exception as err: print(error_dict[type(err)]) # Testers def tester(error_type): raise error_type() # Test handle_error(lambda: tester(ValueError), {ValueError: "bad val", AttributeError: "bad attr"}) handle_error(lambda: tester(AttributeError), {ValueError: "bad val", AttributeError: "bad attr"}) 
bad val bad attr 

As I see you call function without parameter I removed argument for callable from handler. You can still pass argument with use of lambda like above, but it's preferable to change handler's signature as following:

def handle_error(callable_: Callable, error_dict: dict, *args): try: callable_(*args) 
Sign up to request clarification or add additional context in comments.

2 Comments

The main problem is that function should be generic and number of excepts can vary depending on the function call. This do not solve the problem.
Example is meant to be applied to your idea, not a copy-paste solution of what you're doing. If you want fully implemented solution, I'll update accordingly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.