Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch all PHP errors?

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)?

like image 424
StoneHeart Avatar asked Dec 22 '10 23:12

StoneHeart


4 Answers

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

like image 73
Andreas Avatar answered Oct 12 '22 12:10

Andreas


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()

like image 39
Luca C. Avatar answered Oct 12 '22 12:10

Luca C.


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...
}
like image 10
user883992158 Avatar answered Oct 12 '22 12:10

user883992158


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();
}
like image 7
BR1COP Avatar answered Oct 12 '22 10:10

BR1COP