PHP 8.5.0 Alpha 4 available for testing

Voting

: five plus three?
(Example: nine)

The Note You're Voting On

triplepoint at gmail dot com
15 years ago
As noted below, it's important to realize that unless caught, any Exception thrown will halt the script. So converting EVERY notice, warning, or error to an ErrorException will halt your script when something harmlesss like E_USER_NOTICE is triggered.

It seems to me the best use of the ErrorException class is something like this:

<?php
function custom_error_handler($number, $string, $file, $line, $context)
{
// Determine if this error is one of the enabled ones in php config (php.ini, .htaccess, etc)
$error_is_enabled = (bool)($number & ini_get('error_reporting') );

// -- FATAL ERROR
// throw an Error Exception, to be handled by whatever Exception handling logic is available in this context
if( in_array($number, array(E_USER_ERROR, E_RECOVERABLE_ERROR)) && $error_is_enabled ) {
throw new
ErrorException($errstr, 0, $errno, $errfile, $errline);
}

// -- NON-FATAL ERROR/WARNING/NOTICE
// Log the error if it's enabled, otherwise just ignore it
else if( $error_is_enabled ) {
error_log( $string, 0 );
return
false; // Make sure this ends up in $php_errormsg, if appropriate
}
}
?>

Setting this function as the error handler will result in ErrorExceptions only being thrown for E_USER_ERROR and E_RECOVERABLE_ERROR, while other enabled error types will simply get error_log()'ed.

It's worth noting again that no matter what you do, "E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT" will never reach your custom error handler, and therefore will not be converted into ErrorExceptions. Plan accordingly.

<< Back to user notes page

To Top