Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch a PHP fatal (`E_ERROR`) error?

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.

like image 798
too much php Avatar asked Nov 10 '08 06:11

too much php


People also ask

What causes fatal error in PHP?

Fatal Error Fatal errors are ones that crash your program and are classified as critical errors. An undefined function or class in the script is the main reason for this type of error.

What would occur if a fatal error was thrown in your PHP program?

It's an error that caused the script to abort and exit immediately. All statements after the fatal error are never executed. I strongly recommend you use an editor that will alert you to errors as you code. It will safe you a lot of time.

What is E_error?

What is E_ERROR? PHP's E_ERROR typically indicates a major issue with PHP. Normally, PHP may be able to recover from a lesser error and the PHP application could continue to run. However, with E_ERROR , PHP will usually outright fail and stop working entirely.


1 Answers

Log fatal errors using the register_shutdown_function, which requires PHP 5.2+:

register_shutdown_function( "fatal_handler" );  function fatal_handler() {     $errfile = "unknown file";     $errstr  = "shutdown";     $errno   = E_CORE_ERROR;     $errline = 0;      $error = error_get_last();      if($error !== NULL) {         $errno   = $error["type"];         $errfile = $error["file"];         $errline = $error["line"];         $errstr  = $error["message"];          error_mail(format_error( $errno, $errstr, $errfile, $errline));     } } 

You will have to define the error_mail and format_error functions. For example:

function format_error( $errno, $errstr, $errfile, $errline ) {     $trace = print_r( debug_backtrace( false ), true );      $content = "     <table>         <thead><th>Item</th><th>Description</th></thead>         <tbody>             <tr>                 <th>Error</th>                 <td><pre>$errstr</pre></td>             </tr>             <tr>                 <th>Errno</th>                 <td><pre>$errno</pre></td>             </tr>             <tr>                 <th>File</th>                 <td>$errfile</td>             </tr>             <tr>                 <th>Line</th>                 <td>$errline</td>             </tr>             <tr>                 <th>Trace</th>                 <td><pre>$trace</pre></td>             </tr>         </tbody>     </table>";     return $content; } 

Use Swift Mailer to write the error_mail function.

See also:

  • $php_errormsg
  • Predefined Constants
like image 128
user259973 Avatar answered Oct 25 '22 16:10

user259973