Reputation:
If the following code returns a fatal error, I get a message on the page I don't want users to see. I want to hide the fatal error message and redirect the user to another page:
$jinput = JFactory::getApplication()->input;
To hide the error message, I just added:
error_reporting(E_NONE);
But how do I catch and redirect a fatal error like this?
Upvotes: 2
Views: 7713
Reputation: 157896
It's a very common misconception, people often confuse error_reporting
with display_errors
setting. You need the latter.
ini_set('display_errors', 0);
is what actually hides errors from site visitors. While error_reporting
must always remain at E_ALL
.
This idea violates the most basic regulation of HTTP protocol. A page where irrecoverable error occurs, MUST return a 5xx status code, not 3xx. Therefore you should never do any redirect. A 5xx status code must be returned (i.e. 500) and anything you want to show on this page must be shown right in place, without redirects.
Given the error is irrecoverable, and all you can do is just show the error page, what you really need here is a site-wide error handler. A code that would catch the error and do everything described above: return 500 HTTP status code, display some generic error page and also, which is very important, log the error message for the future inspection. In order to create such a handler you will need three functions, set_error_handler(), set_exception_handler() and register_shutdown_function(). You can see a simplified example of the code that uses all three functions in my article on PHP error reporting.
Upvotes: 10
Reputation: 94
Basicaly, you can't "catch" fatal errors because they stop program execution. But there is one method to handle them. Register your own shutdown handler and check if last error was fatal.
<?php
function shutdownHandler()
{
$error = error_get_last();
if ($error['type'] == E_ERROR) {
your code goes here;
}
}
register_shutdown_function('shutdownHandler');
Demo: https://eval.in/137869
Upvotes: 1