Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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?

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.

like image 852
mypythonquestions Avatar asked Oct 21 '25 10:10

mypythonquestions


1 Answers

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
like image 120
Abdul Niyas P M Avatar answered Oct 23 '25 23:10

Abdul Niyas P M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!