500 snippets

PHP exception and error handling with register_shutdown_function and set_exception_handler

Tagged blank, page, exception, php, 500  Languages php

PHP has the crappiest error handling I've ever seen. The default behavior is to show all error messages to the user. If you disable this then you get a blank screen instead. The trick is to register an error handler with register_shutdown_function, which is then called if for example memory is exhausted. You could perhaps also use an ErrorDocument 500, but that didn't work for me.

Here's the code I've used to handle both application exceptions and errors, such as memory limit exceeded. The trick is to have a global variable that indicates whether the script was run successfully or not. Add your code here: "Insert your buggy code here".

$no_errors_detected = false;

class DispatchErrors 
    static function handleException($exception) 

        header( 'Location: /error500.html' );
    static function handleShutdown()
        global $no_errors_detected;
        if (!$no_errors_detected)
            header( 'Location: /error500.html' );

register_shutdown_function(array('DispatchErrors', 'handleShutdown'));
set_exception_handler(array('DispatchErrors', 'handleException'));

# handleShutdown will be called
#range(0, 10000000000000000000);

# handleException will be called
#throw new Exception("abcd");

# Insert your buggy code here

$no_errors_detected = true;

Tracking 404 and 500 with Google Analytics

Tagged 404, 500, analytics, track, google  Languages javascript

New Google Analytics

_gaq.push(['_trackEvent', 'HTTP status', '404', '/xxx/what-a-fish']);

Old Google Analytics

Tracking 404 and 500 errors with Google Analytics is documented here, but I tend to forget so I'm putting the information here:

// 404
pageTracker._trackPageview("/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer);

// 500
pageTracker._trackPageview("/500.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer);


In Rails use the response status code to track any HTTP errors:

<% if response.status != 200 %>
_gaq.push(['_trackEvent', 'HTTP status', '<%= response.status %>', '<%= request.fullpath %>']);
<% end %>