简体   繁体   English

最好直接或从记录器中引发错误

[英]Better to raise an error directly or from within a logger

Which of the following two methods of raising an error is preferred?以下哪两种引发错误的方法是首选?

def _fetch_data(self):
    if self.from_cache:
        logger.debug('Trying to load local file %s...' % self.fp)
        # Grab the data from a local file
        if not os.path.exists(self.fp):

            # first way -- from logger
            logger.error('ERROR: Local file {self.fp} does not exist')

            # second way -- directly raising
            raise SystemExit(f"ERROR: Local file {self.fp} does not exist")

Why is one approach preferred over the other?为什么一种方法优于另一种方法?

One of them prints and takes no action (implying the issue is non-fatal), the other actually attempts to terminate the program (though the idiomatic approach in this case would just be sys.exit(f"ERROR: Local file {self.fp} does not exist") ; it's equivalent to the raise , but slightly clearer in intent).其中一个打印并且不采取任何行动(暗示问题不是致命的),另一个实际上尝试终止程序(尽管在这种情况下惯用的方法只是sys.exit(f"ERROR: Local file {self.fp} does not exist") ;它等同于raise ,但在意图上稍微清晰一些)。

Choose the one that makes sense in context;选择一个在上下文中有意义的; if the file is necessary to continue operation, raise an exception (log first if you like), if it's non-fatal with a reasonable way of continuing operation, you can just log.如果文件是继续操作所必需的,则引发异常(如果您愿意,请先记录),如果继续操作的合理方式不是致命的,您可以只记录。

Note that SystemExit implies it's really fatal (people shouldn't be trying to catch that typically).请注意SystemExit意味着它真的很致命(人们通常不应该试图抓住它)。 Often, it's better to raise some other, more descriptive, less "implies definitely fatal" exception in case the caller knows a good way to handle the problem.通常,如果调用者知道处理问题的好方法,最好提出其他一些更具描述性、更少“暗示绝对致命”的异常。

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

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