我正在运行一个编程并得到预期的 ValueError 输出:
ValueError: {'code': -123, 'message': 'This is the error'}
我不知道如何解析这些数据并只获取代码(或消息)值。我怎样才能获得 ValueError 的
code
值?
我尝试过以下方法:
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'
执行此操作的 Python 方式是什么?
所做的一件事是获取字符串索引,但我不想这样做,因为我觉得它不是很Pythonic。
args
属性,它是给予异常构造函数的tuple
参数。
>>> 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
values()
,而不是
e
。试试这个:try:
ValueError= {'code': -123, 'message': 'This is the error'}
Value = ValueError.get('code')
print Value
except Exception as e:
pass