tags:

views:

9036

answers:

6

I can use set_error_handler() to catch most PHP errors, but it doesn't work for fatal (E_ERROR) errors, such as calling a function that doesn't exist. Is there another way to catch these errors?

I am trying to call mail() for all errors and am running PHP 5.2.3.

+6  A: 

Quickly googling brought up this post on the subject.

eplawless
Won't that only work if display_errors is on?
ejunker
That's messing with black magic.
scotts
+2  A: 

Not really. Fatal errors are called that, because they are fatal. You can't recover from them.

troelskn
+10  A: 

PHP won't provide you with any conventional means for catching fatal errors because they really shouldn't be caught. Any techniques for catching them (like string matching an output buffer) are definitely ill-advised.

In general, emailing yourself when errors are thrown could prove to be problematic, at least if it involves calling the mail() function from within an error handler method. If you had a lot of errors, your mail server would be loaded with work, and you'd have a pretty gnarly inbox.

Alternatively, you might consider running a cron to scan error logs periodically and send notifications accordingly. You might also like to look into system monitoring software, such as Nagios.

keparo
Pfff, I remember those 650.000+ e-mails i got the following morning. Since then my ErrorHandler is capped at 100 emails per webserver.
Bob Fanger
That's not true. You can capture fatal errors with register_shutdown_function.
hipertracker
+2  A: 

You may log your shoutdowns using the register_shutdown_functions , like this

register_shutdown_function('handleShutdown');

function handleShutdown() {
        $error = error_get_last();
        if($error !== NULL){
            $info = "[SHUTDOWN] file:".$error['file']." | ln:".$error['line']." | msg:".$error['message'] .PHP_EOL;
            yourPrintOrMailFunction($info);
        }
        else{
            yourPrintOrMailFunction("SHUTDOWN");
        }
    }
+1  A: 

just came up with this solution (php 5.2.0+): register_shutdown_function('shutdownFunction');

function shutDownFunction() { 
    $error = error_get_last();
    if ($error['type'] == 1) {
        //do your stuff     
    } 
}
periklis
+1  A: 

You cannot throw exception inside registered shutdown function like that:

<?php
function shutdown() {
 if (($error = error_get_last())) {
   ob_clean();
   throw new Exception("fatal error");
  }
}

try {
  $x = null;
  $x->method()
} catch(Exception $e) {
  # this won't work
}
?>

But you can capture and redirect request to another page.

<?php
function shutdown() {
 if (($error = error_get_last())) {
   ob_clean();
   # raport the event, send email etc.
   header("Location: http://localhost/error-capture");
   # from /error-capture, you can use another redirect, to e.g. home page
  }
}
register_shutdown_function('shutdown');

$x = null;
$x->method()
?>
hipertracker