23

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
  • 8,645
  • 5
  • 50
  • 53
StoneHeart
  • 15,790
  • 32
  • 67
  • 84

5 Answers5

20

As of PHP 8 the best way to catch any and 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
  • 325
  • 3
  • 17
17

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.
  • 11,714
  • 1
  • 86
  • 77
  • 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
15

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,305
  • 4
  • 41
  • 60
8

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,764
  • 3
  • 44
  • 61
BR1COP
  • 321
  • 2
  • 5
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
  • 15,064
  • 15
  • 65
  • 105