piglei / one-python-craftsman

来自一位 Pythonista 的编程经验分享,内容涵盖编码技巧、最佳实践与思维模式等方面。

Home Page:https://www.piglei.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

第六篇-上下文管理器改善异常处理流程的疑问

douchen opened this issue · comments

class raise_api_error:
    """captures specified exception and raise ApiErrorCode instead

    :raises: AttributeError if code_name is not valid
    """
    def __init__(self, captures, code_name):
        self.captures = captures
        self.code = getattr(error_codes, code_name)

    def __enter__(self):
        # 该方法将在进入上下文时调用
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # 该方法将在退出上下文时调用
        # exc_type, exc_val, exc_tb 分别表示该上下文内抛出的
        # 异常类型、异常值、错误栈
        if exc_type is None:
            return False

        if exc_type == self.captures:
            raise self.code from exc_val
        return False

这里的 raise self.code from exc_val 是啥意思?from exc_val 没看懂。

raise ... from ... 是链式抛出异常的语法,详见:https://stackoverflow.com/questions/24752395/python-raise-from-usage

在这里,self.code 是一个异常对象,exc_val 也是一个异常对象。raise self.code from exc_val 表示抛出 self.code 异常,但同时标明上级异常是 exc_val