Reputation: 40735
When my script starts, I have:
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
And then, I register my custom error handler with PHP:
function handleError($code, $text, $file, $line) {
echo "&%!!";
return true;
}
set_error_handler('handleError');
Next, there comes some code that produces an error like this:
Fatal error: Call to undefined method DB::getInstanceForDB() in /Applications/MAMP/htdocs/mysite/classes/Test.php on line 32
I keep getting the standard PHP error message box with call stack and everything on my site, no matter if I specify a custom error handler or not. Any idea what's wrong?
Edit: No matter if I return true or not, it doesn't call my custom handler.
Upvotes: 4
Views: 3874
Reputation: 1276
The accepted answer is wrong because a shutdown function is called on all shutdowns, including those handled elsewhere, or just when a page finishes successfully.
I ended up with this, in addition to using set_exception_handler and set_error_handler:
// from http://www.php.net/manual/en/function.set-error-handler.php
define('FATAL', E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING);
register_shutdown_function('shutdown');
// Handles "fatal" errors e.g. Syntax errors
function shutdown() {
// Only if there was an fatal error, this is run on all execution endpoints
$error_info = error_get_last();
if ($error_info !== null && ($error_info['type'] & FATAL)) {
# stack trace set to empty array, as generating one here is useless
[[ do stuff like emailing someone]]
}
}
Upvotes: 3
Reputation: 43804
First, you need to make your error handling function return true. From set_error_handler:
If the function returns FALSE then the normal error handler continues.
Second, be aware that fatal errors aren't handled by set_error_handler
. You need to use register_shutdown_function as well. So your code should look like this:
// Handles non-fatal errors
function handleError($code, $text, $file, $line) {
var_dump($code);
return true;
}
set_error_handler('handleError');
// Handles fatal errors
function fatalShutdown() {
var_dump(error_get_last());
}
register_shutdown_function('fatalShutdown');
Upvotes: 8
Reputation: 401022
In your question, you're telling you are getting a Fatal Error.
I don't think you can catch those, as they are... well... Fatal.
Quoting set_error_handler
:
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 ofE_STRICT
raised in the file whereset_error_handler()
is called.
Upvotes: 0