Handling every PHP error

Or, gotta catch ’em all.

Okay, I’m just going to throw this out there: You can’t reasonably account for every possible error. That’s just unrealistic. However, you can sure make a catch-all to alert you of any you haven’t foreseen, and then, you know, update your code to handle those conditions at your leisure.

error_reporting( E_ALL | E_NOTICE );
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
    // Handle error

But wait, you say, aren’t there certain errors PHP can’t handle from within itself? And you’re right! Parse errors, fatal errors, uncaught exceptions — things like that. So what can you do?

Well, from a CLI perspective, you can parse the program’s output for those errors, and have it notify you when they occur. I have a shell script I run my crons through, which is basically just this:

"$@" 2>&1 >/dev/null | /usr/bin/php catch_errors.php

Which I run like this:

./catch_errors php myscript.php

The stderr output from myscript.php gets piped to catch_errors.php, which checks for specific string occurances:

$input = "";
// read from stdin
$fd = fopen("php://stdin", "r");
while (!feof($fd)) {
    $input .= fread($fd, 1024);
if ( preg_match( '/fatal error|parse error/i', $input ) ) {
    // Handle error