Home > Back-end >  The most pythonic way of handling exceptions [closed]
The most pythonic way of handling exceptions [closed]

Time:09-18

I've got this code:

normalize_data['key1'] = json.loads(normalize_data.get('key1', ''))
normalize_data['key2'] = [key for key in
                                json.loads(normalize_data.get('key2', '[]'))]
normalize_data['key3'] = [json.loads(normalize_data.get('key3', ''))]
normalize_data['key4'] = [json.loads(normalize_data.get('key4', ''))]

As you can see, every key processes differently. If any key will be missing, it will raise JSONEncodeError. If any value of any key will be in wrong format, it will raise TypeError. What is the most pythonic way of handling those? I tried putting this before the code above:

for key in ['key1', 'key2', 'key3', 'key4']:
    if key not in normalize_data:
        raise serializers.ValidationError({'error': f'Field {key} is missing'})
    try:
        json.loads(normalize_data[key])
    except TypeError:
        raise serializers.ValidationError({'error': f'Wrong format of {key}'})

But I don't really like it. Thanks everybody.

CodePudding user response:

There will be doubters but I would do it this way:-

for key in ['key1', 'key2', 'key3', 'key4']:
  try:
    json.loads(normalize_data[key])
  except TypeError:
    raise serializers.ValidationError({'error': f'Wrong format of {key}'})
  except KeyError:
    raise serializers.ValidationError({'error': f'Field {key} is missing'})

CodePudding user response:

Maybe:

for key in ['key1', 'key2', 'key3', 'key4']:
    try:
        json.loads(normalize_data[key])
    except KeyError:
        raise serializers.ValidationError({'error': f'Field {key} is missing'})
    except TypeError:
        raise serializers.ValidationError({'error': f'Wrong format of {key}'})     
  • Related