【问题标题】:Exception that emails stack trace when raised引发时通过电子邮件发送堆栈跟踪的异常
【发布时间】:2016-05-08 17:11:40
【问题描述】:

我希望有一个例外,在提出时总是发送电子邮件。至于现在,我打算把那个代码放到__init()

import sendmail
import configparser


def MailException(BaseException):
    """
    sends mail when initiated
    """
    def __init__(self, message, config=None):
        # Call the base class constructor with the parameters it needs
        BaseException.__init__(message)

        if config is None:
            config = configparser.RawConfigParser()
            config.read('mail.ini')
            config = config['email']

        text = 'exception stack trace + message'

        sendmail.sendMail(text=text, config=config['email'], title='Alert')

我明确希望在此处发送邮件,而不是在我创建的每个例外块中。因此我想知道如何获取堆栈跟踪,代码必须与 Python 2.7 兼容。

我唯一能找到的是traceback,但这显然只适用于except: 领域——或者有没有办法在异常类中实现它?还有其他想法吗?

【问题讨论】:

    标签: python python-2.7 exception


    【解决方案1】:

    首先,请注意(根据the docs)你不应该继承BaseException

    其次,您可以定义一个新的sys.excepthook(参见例如Python Global Exception Handling),而不是在异常本身中实现该逻辑,然后您可以访问完整的回溯:

    import sys
    
    
    class MailException(Exception):
        pass
    
    
    def mailing_except_hook(exctype, value, traceback):
        if exctype == MailException:
            ...  # do your thing here
        else:
            sys.__excepthook__(exctype, value, traceback)
    
    sys.excepthook = mailing_except_hook
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多