Tracking 404 and 500 with 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:
1 // 404 2 pageTracker._trackPageview("/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer); 3 4 // 500 5 pageTracker._trackPageview("/500.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer);
In Rails I set the response code and use that instead of hardcoding it in the view:
1 <% if response.status != 404 %> 2 pageTracker._trackPageview(); 3 <% else %> 4 pageTracker._trackPageview("/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer); 5 <% end %>
PHP exception and error handling with register_shutdown_function and set_exception_handler
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”.
1 $no_errors_detected = false; 2 3 class DispatchErrors 4 { 5 static function handleException($exception) 6 { 7 Logging::error($message); 8 9 header( 'Location: /error500.html' ); 10 } 11 12 static function handleShutdown() 13 { 14 global $no_errors_detected; 15 16 if (!$no_errors_detected) 17 { 18 header( 'Location: /error500.html' ); 19 } 20 } 21 } 22 23 register_shutdown_function(array('DispatchErrors', 'handleShutdown')); 24 set_exception_handler(array('DispatchErrors', 'handleException')); 25 26 # handleShutdown will be called 27 #range(0, 10000000000000000000); 28 29 # handleException will be called 30 #throw new Exception("abcd"); 31 32 # Insert your buggy code here 33 34 $no_errors_detected = true;