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)?
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
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()
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...
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With