15

I need a solution to catch all PHP fatal errors, exceptions, warnings, etc. and have a callback.

I want to display a friendly version of the error to the user and log that error.

I'm thinking about using a text file per day for logging error.

Any suggestion or PHP class (library)?

Maxime
  • 7,970
  • 4
  • 49
  • 50
StoneHeart
  • 14,982
  • 31
  • 66
  • 83

5 Answers5

13

This makes almost all errors become catchable instance of ErrorException:

set_error_handler(function($errno, $errstr, $errfile, $errline ){
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});

use it before of the code that can give errors, for instances at the very top of your php file or in a common header included

Limits: Severest errors (PHP engine, server, syntax) cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called compromise it.

But, if syntax is correct and server don't broke, these errors should not appear.

If needed, you could workaround it with the register_shutdown_function() and error_get_last()

Luca C.
  • 9,980
  • 1
  • 77
  • 73
  • 1
    Note that not all PHP errors can be handled with a user-defined error handler using `set_error_handler`. See https://stackoverflow.com/questions/8527894/set-error-handler-doenst-work-for-fatal-error#answer-8527924 – tonix Jun 17 '18 at 21:07
13

php method: set_error_handler might be what you are looking for.

More at: http://www.php.net/manual/en/function.set-error-handler.php

and at: http://php.net/manual/en/book.errorfunc.php

Andreas
  • 5,267
  • 4
  • 40
  • 59
7

Try launch this web page, you should see "Message: Division by Zero".

// Set Error Handler

set_error_handler (
    function($errno, $errstr, $errfile, $errline) {
        throw new ErrorException($errstr, $errno, 0, $errfile, $errline);     
    }
);

// Trigger an exception in a try block

try {
    $a = 3/0;
    echo $a;
}
catch(Exception $e) {
    echo 'Message: ' .$e->getMessage();
}
halfpastfour.am
  • 5,475
  • 3
  • 40
  • 59
BR1COP
  • 193
  • 1
  • 5
5

As of PHP 7 the best way to catch all Exceptions is to catch the Throwable interface which "is the base interface for any object that can be thrown via a throw statement". So your code would look something like this.

try {
    # code...
} catch (\Throwable $th) {
    # code...
}
user883992158
  • 119
  • 4
  • 12
0

I quite like the error handling from the kohana framework. You'd have to do a bit of work to pull it out though.

http://kohanaframework.org/

It will allow you to do error logging to a file and email a recipient. It also enables you to redirect to your friendly error page.

Jason
  • 14,518
  • 15
  • 63
  • 105