Is it possible to have PHP stop execution upon a notice/warning, globally?
We run a development server with a lot of sites on, but want to force our developers to fi
The other solutions implement a custom error handler which overrides the default error logging mechanism. That means when we set a custom error handler, the notice / warning is not printed anymore in the default way, so we change more than just "stop script execution upon notice / warning".
However, I needed a way to still print the message - in my case in PHP CLI - since the output is then parsed by another program. So I didn't want to print the message in some way but in the exact same way than PHP usually does it. I just wanted to stop the PHP CLI process with an exit code of != 0 right after a notice / warning was printed, and do not change anything else.
Unfortunately, there does not seem to be a default way of exiting the script without changing the whole error handling. So I needed to reimplement the default error handler (which is implemented in C) in PHP.
For this, I looked into the default error printing mechanism in PHP's source code and ported the relevant pieces from C to PHP to get the following error handler, which I want to share with you in case you need something similar:
set_error_handler(
function($errNo, $errStr, $errFile, $errLine) {
$error_type_str = 'Error';
// Source of the switch logic: default error handler in PHP's main.c
switch ($errNo) {
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
$error_type_str = "Fatal error";
break;
case E_RECOVERABLE_ERROR:
$error_type_str = "Recoverable fatal error";
break;
case E_WARNING:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_USER_WARNING:
$error_type_str = "Warning";
break;
case E_PARSE:
$error_type_str = "Parse error";
break;
case E_NOTICE:
case E_USER_NOTICE:
$error_type_str = "Notice";
break;
case E_STRICT:
$error_type_str = "Strict Standards";
break;
case E_DEPRECATED:
case E_USER_DEPRECATED:
$error_type_str = "Deprecated";
break;
default:
$error_type_str = "Unknown error";
break;
}
fwrite(STDERR, "PHP $error_type_str: $errStr in $errFile on line $errLine\n");
exit(1);
},
E_ALL
);