我希望有类似自定义错误代码/消息数据库的东西,并在引发异常(在Python 3.4中)时使用它。所以我做了以下事情:
class RecipeError(Exception):
# Custom error codes
ERRBADFLAVORMIX = 1
ERRNOINGREDIENTS = ERRBADFLAVORMIX + 1
# Custom messages
ERRMSG = {ERRBADFLAVORMIX: "Bad flavor mix",
ERRNOINGREDIENTS: "No ingredients to mix"}
raise RecipeError(RecipeError.ERRMSG[RecipeError.ERRBADFLAVORMIX])
这可以按预期工作,但raise
语句只是怪异的。当然,我可以以更紧凑的方式存储值,但我真正想知道的是:我可以执行类似raise RecipeError(code)
的操作并将消息传递给RecipeError吗?
答案 0 :(得分:3)
不确定。异常类只是普通类,因此您可以定义自己的__init__
来适当调用super
:
class RecipeError(BaseException):
# existing stuff
def __init__(self, code):
super().__init__(self, RecipeError.ERRMSG[code])
您可能还想保存代码:
class RecipeError(BaseException):
# existing stuff
def __init__(self, code):
msg = RecipeError.ERRMSG[code]
super().__init__(self, msg)
self.code, self.msg = code, msg
看看存储在标准库的异常中的信息(在3.4中相当不错,尽管还有更多变化......)看看什么样的东西可能对藏匿有用。 / p>
一些旁注:
首先,使用子类而不是错误代码可能更好。例如,如果有人想编写捕获ERRBADFLAVORMIX
但不是ERRNOINGREDIENTS
的代码,则必须执行此操作:
try:
follow_recipe()
except RecipeError as e:
if e != RecipeError.ERRBADFLAVORMIX:
raise
print('Bad flavor, bad!')
或者,如果您使用了子类:
try:
follow_recipe():
except BadFlavorRecipeError as e:
print('Bad flavor, bad!')
这就是为什么Python不再具有您需要打开的OSError
值errno
的整体FileNotFoundError
,而是具有单独的子类,如BaseException
。
如果您确实想使用错误代码,可能需要考虑使用Enum
或one of the fancier enum types on PyPI,以便更容易将自定义字符串附加到每个错误代码。
你几乎从不想继承{{1}},除非你特意设法确保你的例外没有被抓住。