从PHP异常__destruct()方法发送错误报告是个好主意还是坏主意? [英] Is sending error report from PHP Exception __destruct() method a Good or Bad Idea?

查看:166
本文介绍了从PHP异常__destruct()方法发送错误报告是个好主意还是坏主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的应用程序设计一个错误处理系统。
我想以例外为基础,并且希望通过电子邮件收到有关我没有想到的每个例外的通知。

I am designing an error handling system for my application. I want to base it on exceptions, and I want to get notified by email about every exception which I had not expected.

我想到了一个类:

class My_Exception extends Exception {

    private $sendErrorReport = true;

    public function __destruct() {
        if ($this->sendErrorReport) {
              // send the error report by email
        }            
    }

    public function cancelErrorReport() {
        $this->sendErrorReport = false;
    }

} 

我想做类似的事情

try { 
   do_something_that_can_throw_exception();
catch (My_Exception $e) {
   if ($e->getCode() == I_KNOW_WHAT_TO_DO ) {
        react_to_exception();
        $e->cancelErrorReport();   
   } else {
        show_error_message($e->getMessage());
   }
}

因此,基本上,当发生异常时,系统知道该怎么做,它不会打扰我作为开发人员。但是,如果系统无法处理某些问题,则会收到通知。
我不想将通知我的代码放在catch子句中,因为我确定我会忘记它的地方...

So, basically, when exception happens, and the system kows what to do, it does not bother me as a developer. But when there is something the system can't handle, then I am notified. I do not want to place the code that notifies me in the catch clause, cause I'm sure I WILL forget it somewhere...

我可以吗确定将调用异常__destuct方法?

Can I be sure that the exception __destuct method will be called?

__ destruct异常方法是实现此目标的好方法吗?

Is the __destruct method of exception a good way to achieve this goal?

是否有更好的方法可以实现该目标?

Is there a better way I could achieve that?

推荐答案

为什么不简单地向其中添加方法调用电子邮件时发送电子邮件的Exception类?
类似的东西:

Why don't you simply add a method to the Exception class to send an email when it's called? Something like:

class My_Exception extends Exception {

    private $sendErrorReport = true;

    public function __destruct() {
        if ($this->sendErrorReport) {
              // send the error report by email
        }            
    }

    public function cancelErrorReport() {
        $this->sendErrorReport = false;
    }

    public function sendEmail()
    {
        mail(....., $this->getMessage());
    }

} 

,然后执行以下操作:

and then you do something like:

try { 
   do_something_that_can_throw_exception();
catch (My_Exception $e) {
   if ($e->getCode() == I_KNOW_WHAT_TO_DO ) {
        react_to_exception();
        $e->cancelErrorReport();   
   } else {
        $e->sendEmail();
   }
}

这篇关于从PHP异常__destruct()方法发送错误报告是个好主意还是坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆