Can register_shutdown_function() and set_error_handler() catch the same error?

Viewed 835

If I have the following defined in the same script:

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

Are there any error types that would trigger both handlers?

1 Answers

The shutdown function will be executed when the script execution is finished whether there is an error, exception or not. It has nothing to do with errors or exceptions, errors or exceptions don't trigger it , and it does not catch them, it will be called anyway at the end of the script, so it is useful if you want to do some work even if an exception or fatal error happened because error handler function does not get executed if Fatal error or exception happened.

The error handler function will be executed when error is triggered. This is quoted from the manual

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

<?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

scenario 1 (no errors) outputs

foo 
shutdownFunction is called

scenario 2(error is triggered) outputs

errorHandlerFunction is called 
shutdownFunction is called 

scenario 3 (Fatal error is triggered) outputs

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

scenario 4 (exception is thrown) outputs

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 

see for yourself https://eval.in/1073642

Related