【问题标题】:Creating a error handler class in php在 php 中创建错误处理程序类
【发布时间】:2013-02-19 05:11:36
【问题描述】:

我最近一直在询问有关异常和处理异常等问题,which as recently best explained to me in this question.我现在的问题是我将如何使用

set_exception_handler();

在一个类中设置一个错误处理类在php中,当抛出错误时由这个类处理。正如定义所述:

如果在 try/catch 块中未捕获到异常,则设置默认异常处理程序。调用 exception_handler 后将停止执行。

我在想我可以这样做:

class Test{
    public function __construct(){
        set_exception_handler('exception');
    }

    public function exception($exception){
        echo $exception->getMessage();
    }
}

但问题是,如果用户正在设置应用程序或使用应用程序中的任何 API,他们必须做一个整体:new Test();

那么我该如何编写一个异常处理程序类:

  1. 在抛出异常时自动调用以处理“未捕获”异常。
  2. 以可扩展的 OOP 方式完成。

我所展示的方式是我能想到的唯一方式。

【问题讨论】:

  • 这确实应该在官方PHP帮助中,标记为the best practices!

标签: php exception error-handling


【解决方案1】:

为了让您的课程正常工作,您的构造函数中的行应该是:

// if you want a normal method        
set_exception_handler(array($this, 'exception'));

// if you want a static method (add "static" to your handler method
set_exception_handler(array('Test', 'exception'));

【讨论】:

  • 值得一提的是,一般来说,当您想将函数名传递给某物并且该函数实际上是一个对象方法时,您可以使用此处显示的语法。也就是说,这个解决方案适用于其他需要函数名的 PHP 方法。
  • 我提前看到了我的错误,我担心的是,如果用户正在设置应用程序,这又是另一个类,他们必须将其称为“新”对象。
  • 我知道这是很久以前的事了,但最好使用static::class 而不仅仅是静态方法的类名。通过使用它,您可以支持命名空间。 set_exception_handler(array(static::class, 'exception'));
【解决方案2】:

每个人都认为使用 set_exception_handler 会捕获 PHP 中的所有错误,但事实并非如此,因为 set_exception_handler 没有处理某些错误,处理所有类型错误的正确方法必须是:

 //Setting for the PHP Error Handler
 set_error_handler( call_back function or class );

 //Setting for the PHP Exceptions Error Handler
 set_exception_handler(call_back function or class);

 //Setting for the PHP Fatal Error
 register_shutdown_function(call_back function or class);

通过设置这三个设置,您可以捕获 PHP 的所有错误。

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 2011-11-02
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    相关资源
    最近更新 更多