mypythonquestions
mypythonquestions

Reputation: 93

How to parse a ValueError in Python without string parsing?

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:

What is the pythonic way of doing this?

Edit

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

Answers (3)

user459872
user459872

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

Mevlana Ayas
Mevlana Ayas

Reputation: 21

ValueError is a dict type. So you can use e.get("key") to reach any field inside dict.

Upvotes: 1

Kian
Kian

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

Related Questions