Напишите декоратор, который оборачивает функцию в блок try-except и выводит ошибку, если произошла ошибка
def decorator_try_except(func):
def wrapper(*args,**kwargs):
try:
return func(*args, **kwargs)
except Exception as error:
print(f"Found 1 error during execution of your function: {type(error).__name__} no such key as '{error.args[0]}'")
return wrapper
@decorator_try_except
def some_function_with_risky_operation(data):
print(data['key'])
some_function_with_risky_operation({'foo': 'bar'})
Вывод функции должен быть:
Found 1 error during execution of your function: KeyError no such key as 'foo'
Вместо этого выводит:
Found 1 error during execution of your function: KeyError no such key as 'key'
Ответы (1 шт):
Автор решения: Aleksandr Fetisov
→ Ссылка
@decorator_try_except
def some_function_with_risky_operation(data):
return data.get('key', None)
result = some_function_with_risky_operation({'foo': 'bar'})
if result is not None:
print(result)
else:
print("Key not found")