In order to avoid using numerous try:except blocks like the one below,
I’ve created a dedicated function that should handle any exception,
The thing is since the data it should handle does not exist, so it fail before it reaches the handle function.
So, basically making the handle function obsolete, and making me have to use a lot of try:except blocks like before.
Furthermore, I can’t use one try:except block, since not all of the parameters are needed all the time.
What is the better way to achieve this ?
- Initial blocks:
try:
print('timestamp', event['timestamp'])
except:
print('No timestamp value recived')
try:
print('description', event['description'])
except:
print('No description value received')
- 2nd rewrite:
Code example:
def get_data(event):
status = handle_exception(event['status'])
print(status)
def handle_exception(parameter):
try:
result = parameter
except:
result = 'NONE'
return result
>Solution :
Assuming event is a dictionary or alike, you could use event.get('status') to retrieve a value or a None if the key-mapping doesn’t exist.