【问题标题】:How to parse a ValueError in Python without string parsing?如何在没有字符串解析的情况下解析 Python 中的 ValueError?
【发布时间】:2019-05-03 10:57:01
【问题描述】:

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

这样做的pythonic方式是什么?

编辑

的一件事是获取字符串索引,但我不想这样做,因为我觉得它不是很pythonic。

【问题讨论】:

    标签: python python-3.x error-handling valueerror


    【解决方案1】:

    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 "<stdin>", line 1, in <module>
    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
    

    【讨论】:

      【解决方案2】:

      ValueError 是一个 dict 类型。 所以你可以使用 e.get("key") 到达dict中的任何字段。

      【讨论】:

      • 我明白了。谢谢你。 get 似乎不起作用,就像 AttributeError: 'ValueError' object has no attribute 'get' 一样。 @Abdul 回答很适合我的情况。
      【解决方案3】:

      您应该直接从您的字典中获取您的values(),而不是e。试试这个:

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

      【讨论】:

      • 我只是使用except ValueError as e。我不是在创建字典本身。 我相信它来自我正在调用的 API。如果我无法编辑",还有其他方法吗?
      • 我明白了。谢谢你。 get 似乎不起作用,就像 AttributeError: 'ValueError' object has no attribute 'get'。 @Abdul 回答很适合我的情况。
      • 您应该避免使用 ValueError 名称,因为这是一个内置异常名称。
      • 我应该用什么代替,在哪里?我应该说except error as e 或类似的话吗?我以为你应该except (errorname)?抱歉,我是新手。
      • 您可以简单地重命名它。因为像ValueErrorlist 这样的名称不会混淆解释器,但它可能会混淆阅读您的代码的人。但是,在您的情况下,您直接从 API 读取。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2021-04-19
      • 1970-01-01
      相关资源
      最近更新 更多