如何在Python中解析ValueError而不需要字符串解析?

问题描述 投票:0回答:3

我正在运行一个编程并得到预期的 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。

python python-3.x error-handling valueerror
3个回答
3
投票

ValueError

异常类有一个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



1
投票


0
投票
values()

,而不是

e
。试试这个:

try: ValueError= {'code': -123, 'message': 'This is the error'} Value = ValueError.get('code') print Value except Exception as e: pass

© www.soinside.com 2019 - 2024. All rights reserved.