Search code examples
pythonpython-3.xerror-handlingvalueerror

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.


Solution

  • 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