简体   繁体   English

最佳实践:在 KeyError 上,打印或引发自定义消息的 KeyError?

[英]Best practice: On KeyError, print or raise KeyError for a custom message?

Suppose I have a dict like:假设我有一个像这样的dict

envs = {
    "prod": "PRODSERVERNAME",
    "test": "TESTSERVERNAME",
    "dev": "DEVSERVERNAME"
}

and I want to change the message the KeyError returns, what I've been seeing in web articles on the subject is to print out the new message, like:我想更改KeyError返回的消息,我在 web 文章中看到的有关该主题的内容是打印出新消息,例如:

try:
    server = envs[env]
except KeyError:
    print(
        f'No environment found for "{env}"; env must be one of the following: {", ".join(envs.keys())}'
        )

It seems to me that I'd still want to throw appropriate error (in this case, KeyError to be thrown), just with more helpful/specific information about that error.在我看来,我仍然想抛出适当的错误(在这种情况下,将抛出KeyError ),只是提供有关该错误的更多有用/具体信息。 With that assumption (please correct me if there is a best practice around this), I'd implement that intention like:有了这个假设(如果有最佳实践,请纠正我),我会像这样实现这个意图:

try:
    server = envs[env]
except KeyError:
    raise KeyError(
        f'No environment found for "{env}"; env must be one of the following: {", ".join(envs.keys())}'
        )

But excepting an error only to throw the error of the same type seems inelegant at best, and janky at worst.但是排除错误只是抛出相同类型的错误充其量似乎是不优雅的,最坏的情况下是简陋的。

My question is: What is the appropriate way to handle situations like this?我的问题是:处理这种情况的适当方法是什么? Is there any documentation I may have missed on best practices related to this topic?关于与此主题相关的最佳实践,是否有任何我可能遗漏的文档?

Thanks in advance.提前致谢。

I'd say it's a matter of preference.我会说这是一个偏好问题。 Your code will work just fine and will be readable as is.您的代码将工作得很好,并且可以按原样阅读。 It's just a matter of what you try to accomplish.这只是您尝试完成的事情的问题。

In this specific case you don't really want to handle KeyError , but rather raise a custom exception when one env var is missing.在这种特定情况下,您真的不想处理KeyError ,而是在缺少一个环境变量时引发自定义异常。 So just do it.所以就去做吧。

class CustomException(KeyError):
    def __init__(self, missing, allowed):
        self.value = f"No environment found for {missing}; env must be one of the following: {allowed}"

    def __str__(self):
        return repr(self.value)


server = envs.get(env)
if not server:
    raise CustomException('a', ', '.join(['a', 'b', 'c']))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM