Reputation: 93
I am running a programming and getting an expected ValueError output of:
ValueError: {'code': -123, 'message': 'This is the error'}
I cannot figure out how to parse this data and just take the code (or message) value. How can I just get the code
value of the ValueError?
I have tried the following:
e.code
AttributeError: 'ValueError' object has no attribute 'code'
e['code']
TypeError: 'ValueError' object is not subscriptable
json.loads(e)
TypeError: the JSON object must be str, bytes or bytearray, not 'ValueError'
What is the pythonic way of doing this?
The one thing that does work is taking the string index, but I do not want to do this, as I feel it is not very pythonic.
Upvotes: 4
Views: 5521
Reputation: 24602
The ValueError
exception class have an args
attribute which is tuple
of arguments given to the exception constructor.
>>> a = ValueError({'code': -123, 'message': 'This is the error'})
>>> a
ValueError({'code': -123, 'message': 'This is the error'})
>>> raise a
Traceback (most recent call last):
File "", line 1, in
ValueError: {'code': -123, 'message': 'This is the error'}
>>> dir(a) # removed all dunder methods for readability.
['args', 'with_traceback']
>>> a.args
({'code': -123, 'message': 'This is the error'},)
>>> a.args[0]['code']
-123
Upvotes: 3
Reputation: 21
ValueError is a dict type. So you can use e.get("key") to reach any field inside dict.
Upvotes: 1
Reputation: 1350
You should get your values()
directly from your dictionary not e
. Try this one:
try:
ValueError= {'code': -123, 'message': 'This is the error'}
Value = ValueError.get('code')
print Value
except Exception as e:
pass
Upvotes: 0