Redirecting to an Error page when a Fatal Error occurs

Permanent Link: Redirecting to an Error page when a Fatal Error occurs 7. April 2009 RSS Feed for comments on RSS-Feed für Kommentare zu: Redirecting to an Error page when a Fatal Error occurs comments feed

Everyone surely has already encountered it: A fatal error on a page that is online including the white page you get to see because of it. There's a nice and easy way of showing an error page instead of a white page if a Fatal Error occurs by using output buffering. According to its documentation, ob_start() supports a callback as first parameter. The cool thing is that this callback is also called in case of a Fatal Error!

Here's how it works:

class Redirector
{
public static function redirectOnError($buffer)
{
$lastError = error_get_last();
if(!is_null($lastError) && $lastError['type'] === E_ERROR) {
header('HTTP/1.1 302 Moved Temporarily');
header('Status: 302 Moved Temporarily');
header('Location: error.php');
exit();
}
return $buffer;
}
}

ob_start(array('Redirector', 'redirectOnError'));
print('Hello');

foobar();

ob_end_flush();

The callback is called in the moment the content is flushed, that's why the flush should always be the last line in your output script if you wanna catch all Fatal errors. Since the callback is always executed, I added a check whether a fatal error occured, since we don't want a redirect when no error occurs. Also keep in mind that the callback has to return the buffered output (that is already passed to the callback as a parameter) which will be printed after its execution. (Note that error_get_last() is PHP >= 5.2.0)

Note: Instead of an 302 redirect, which I used in the example, you could also just output an error message on the same page:

public static function redirectOnError($buffer)
{
$lastError = error_get_last();
if(!is_null($lastError) && $lastError['type'] === E_ERROR) {
header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
$buffer = 'Sorry, an error occured';
}
return $buffer;
}

Thanks to Jakob and Lars for some input and refinements on this blogpost.

4 comments

xaoss Gravatar

xaos
08.04.2009, 15:12 o'clock

Hi Dominik,

very nice code, i never realized that php could handle "fatal errors"..cool.

Thx
xaos

ulis Gravatar

uli
09.04.2009, 11:59 o'clock

An alternative way is to use the register_shutdown_function() function described here:
http://www.eggplant.ws/blog/php/mayday-php-going-down/

Dominik Jungowskis Gravatar

Dominik Jungowski
13.04.2009, 12:04 o'clock

That's a nice way too, indeed. Thanks for the link!

online stock trading gurus Gravatar

online stock trading guru
11.01.2010, 02:07 o'clock


I usually don’t post on Blogs but ya forced me to, great info.. excellent! … I'll add a backlink and bookmark your site.


I'm Out! :)

Write a comment

(will not be published)