如何从python 3中的十进制中获取有用的异常消息?

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

使用Python 2,使用无效字符串创建Decimal会产生一个有用的错误消息:

>>> import decimal
>>> decimal.Decimal('spam')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 547, in __new__
    "Invalid literal for Decimal: %r" % value)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 3872, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: Invalid literal for Decimal: 'spam'

虽然Python 3产生了一条不太有用的消息:

>>> import decimal
>>> decimal.Decimal('spam')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

有没有办法从Python 3中的异常中获取有用的信息,如“Decimal的无效文字:'垃圾邮件'”?

我在darwin上使用Python 2.7.15和Python 3.7.2。

附加物:

看起来Python 2曾经有一个非常有用的十进制消息.InvalidOperation:https://bugs.python.org/issue1770009

这种情况看起来很相似,但大多数情况都超出了我的想法:https://bugs.python.org/issue21227

python-3.x exception decimal invalidoperationexception
1个回答
1
投票

你可以修补decimal模块。

import decimal


def safe_decimal(something):
    try:
        funct_holder(something)
    except Exception as e:
        new_errror = Exception("Hey silly that's not a decimal, what should I do with this? {}".format(something))
        raise new_errror from None


funct_holder = decimal.Decimal
decimal.Decimal = safe_decimal

然后你可以使用猴子修补版本

>>> decimal.Decimal('hello')
Traceback (most recent call last):
  File "<input>", line 12, in <module>
  File "<input>", line 6, in safe_decimal
Exception: Hey silly that's not a decimal, what should I do with this? hello
© www.soinside.com 2019 - 2024. All rights reserved.