在Python中包装异常

34 投票
3 回答
17636 浏览
提问于 2025-04-16 04:54

我正在开发一个发送邮件的库,我希望能够捕捉发送邮件时出现的错误(比如SMTP、Google AppEngine等产生的错误),并把这些错误包装成我自己库里容易处理的错误类型(比如连接错误、发送消息错误等),同时保留原始的错误追踪信息,以便进行调试。在Python 2中,最好的做法是什么呢?

3 个回答

6

这个回答可能有点晚了,但你可以把这个函数放在一个叫做Python装饰器的东西里。

这里有一个简单的速查表,可以帮助你了解不同的装饰器。

下面是一些示例代码,展示了怎么做。只需要把decorator换成你需要的不同方式来捕捉不同的错误。

def decorator(wrapped_function):
    def _wrapper(*args, **kwargs):
        try:
            # do something before the function call
            result = wrapped_function(*args, **kwargs)
            # do something after the function call
        except TypeError:
            print("TypeError")
        except IndexError:
            print("IndexError")
        # return result
    return _wrapper


@decorator
def type_error():
    return 1 / 'a'

@decorator
def index_error():
    return ['foo', 'bar'][5]


type_error()
index_error()
7

使用来自 future.utilsraise_from

下面是相关的示例:

from future.utils import raise_from

class FileDatabase:
    def __init__(self, filename):
        try:
            self.file = open(filename)
        except IOError as exc:
            raise_from(DatabaseError('failed to open'), exc)

在这个包里,raise_from 的实现方式如下:

def raise_from(exc, cause):
    """
    Equivalent to:

        raise EXCEPTION from CAUSE

    on Python 3. (See PEP 3134).
    """
    # Is either arg an exception class (e.g. IndexError) rather than
    # instance (e.g. IndexError('my message here')? If so, pass the
    # name of the class undisturbed through to "raise ... from ...".
    if isinstance(exc, type) and issubclass(exc, Exception):
        e = exc()
        # exc = exc.__name__
        # execstr = "e = " + _repr_strip(exc) + "()"
        # myglobals, mylocals = _get_caller_globals_and_locals()
        # exec(execstr, myglobals, mylocals)
    else:
        e = exc
    e.__suppress_context__ = False
    if isinstance(cause, type) and issubclass(cause, Exception):
        e.__cause__ = cause()
        e.__suppress_context__ = True
    elif cause is None:
        e.__cause__ = None
        e.__suppress_context__ = True
    elif isinstance(cause, BaseException):
        e.__cause__ = cause
        e.__suppress_context__ = True
    else:
        raise TypeError("exception causes must derive from BaseException")
    e.__context__ = sys.exc_info()[1]
    raise e
30

最简单的方法就是用旧的追踪对象重新抛出异常。下面的例子展示了这一点:

import sys

def a():
    def b():
        raise AssertionError("1")
    b()

try:
    a()
except AssertionError: # some specific exception you want to wrap
    trace = sys.exc_info()[2]
    raise Exception("error description"), None, trace

你可以查看raise语句的文档,了解三个参数的详细信息。我的例子会打印出:

Traceback (most recent call last):
  File "C:\...\test.py", line 9, in <module>
    a()
  File "C:\...\test.py", line 6, in a
    b()
  File "C:\...\test.py", line 5, in b
    raise AssertionError("1")
Exception: error description

为了完整起见,在Python 3中,你可以使用raise MyException(...) from e 语法

撰写回答