register_shutdown_function()和set_error_handler()是否可以捕获相同的错误?

时间:2019-01-02 11:50:11

标签: php error-handling

如果在同一脚本中定义了以下内容:

register_shutdown_function('handlerOne');
set_error_handler('handlerTwo');

是否有会同时触发两个处理程序的错误类型?

1 个答案:

答案 0 :(得分:4)

脚本执行完成后,无论是否有错误,异常,都将执行shutdown function。它与错误或异常无关,错误或异常不会触发它,并且不会捕获它们,无论如何都会在脚本结尾处调用,因此如果即使发生异常或致命错误,您也想做一些工作,因为如果发生致命错误或异常,则错误处理程序功能不会执行。

在触发错误时将执行error handler function。这是从手册中引用的

  

以下错误类型无法由用户定义来处理   函数:E_ERROR,E_PARSE,E_CORE_ERROR,E_CORE_WARNING,   E_COMPILE_ERROR,E_COMPILE_WARNING和大多数E_STRICT是在   调用set_error_handler()的文件。

<?php

function shutdownFunction(){
    echo "shutdownFunction is called \n";
} 

function errorHandlerFunction(){
    echo "errorHandlerFunction is called \n";
} 
register_shutdown_function('shutdownFunction');
set_error_handler('errorHandlerFunction');

//echo "foo\n"; // scenario 1 no errors
//echo $undefinedVar; //scenario 2 error is triggered
//undefinedFunction(); //scenario 3 Fatal error is triggered
//throw new \Exception(); //scenario 4 exception is thrown

方案1(无错误)输出

foo 
shutdownFunction is called

场景2(触发错误)输出

errorHandlerFunction is called 
shutdownFunction is called 

场景3(触发致命错误)输出

Fatal error: Call to undefined function undefinedFunction() in /tmp/execpad-b2a446c7f6a6/source-b2a446c7f6a6 on line 15
shutdownFunction is called

场景4(引发异常)输出

Fatal error: Uncaught exception 'Exception' in /tmp/execpad-0b3a18f0ea06/source-0b3a18f0ea06:16
Stack trace:
#0 {main}
thrown in /tmp/execpad-0b3a18f0ea06/source-0b3a18f0ea06 on line 16
shutdownFunction is called 

亲自见https://eval.in/1073642