28

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

5 Answers 5

30

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...
}
Sign up to request clarification or add additional context in comments.

1 Comment

For some reason, bzopen don´t throws a Throable
19

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

1 Comment

Note that not all PHP errors can be handled with a user-defined error handler using set_error_handler. See stackoverflow.com/questions/8527894/…
16

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

Comments

9

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.