简体   繁体   English

更改python未处理异常的行为以发送电子邮件

[英]change behavior of python unhandled Exception to send emails

I want to change the behavior of unhandled Exceptions (all of them) in python to send emails without changing code very much or using special error handlers everywhere. 我想在python中更改未处理的Exceptions(所有这些)的行为,以便在不更改代码的情况下发送电子邮件或在任何地方使用特殊的错误处理程序。

My hope is to subclass Exception and then redefine it at the beginning of a given module. 我希望将Exception子类化,然后在给定模块的开头重新定义它。

So the subclassing is here: 所以子类化在这里:

class ExceptionMailer(Exception):
    def __init__(self, m):
        self.message = m
        send_email(email_address,self.message)

Then at the at the begining of a module I can do this: 然后在模块开始时我可以这样做:

Exception = ExceptionMailer

Then when an Exception is raised an email with it's message is sent. 然后,当引发异常时,将发送带有该消息的电子邮件。 I have gotten this to work strictly for Exception but not for say ValueError . 我已经让它严格地用于Exception但不是说ValueError My hope was that redefining Exception would redefine all the error types but I was clearly wrong. 我希望重新定义Exception会重新定义所有错误类型,但我显然是错的。 Is what I am trying to do possible? 我正在尝试做什么?

In the moment you redefine Exception , all its subclasses were created, so it doesn't affect them: 在重新定义Exception的那一刻,它的所有子类都已创建,因此它不会影响它们:

>>> class A(object):
    def a(self):
        print 'a in A'

>>> class B(A):
    pass

>>> B().a()
a in A
>>> class C(object):
    def a(self):
        print 'a in C'

>>> A = C
>>> B().a()
a in A

Regarding your problem. 关于你的问题。 Take a look at sys.excepthook . 看一下sys.excepthook It allows you to redefine program behavior in case of any uncaught exception. 它允许您在任何未捕获的异常情况下重新定义程序行为。

I want to change the behavior of Exceptions (all of them) ... 我想改变Exceptions的行为(所有这些)......

No, you don't. 不,你没有。 In Python, exceptions are used for flow control. 在Python中,异常用于流控制。 For example, your handler would fire every time a StopIteration is raised, or a comparison function fails, or a library uses an exception to signal something. 例如,每次引发StopIteration时,您的处理程序都会触发,或者比较函数失败,或者库使用异常来发出信号。

Instead, simply wrap your code in 相反,只需将代码包装好即可

try:
   # ... large block of code
except BaseException as e:
   send_email(email_address, e.message)

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

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