Code: Practice Error Awareness

Chapter 8 - Ajax Optimization

It would be a good idea to know when users are frustrated or experiencing trouble outside of slow downloads, such as a JavaScript error or a feature problem. In fact, you might want to know that the user even has her JavaScript turned on. This is actually pretty easy to do using the noscript tag. Consider the markup shown here:

<noscript>
    <span class="error">Error: This site requires JavaScript.</span>
    <img src="http://example.com/errormonitor.php?scriptoff=true" />
</noscript>

The image tag references a server-side script that will record that the user has her JavaScript off. It will be fetched only when the browser has the script off. If her JavaScript is on but you still encounter an error, you might imagine associating an error handler to window.onerror that then makes a call to the server indicating what has happened. Here is the outline of such code:

window.onerror = reportJSError;
function reportJSError(errorMessage,url,lineNumber)
{
    /* form payload string with error data */
    payload = "url="+url;
    payload += "message=" + errorMessage;
    payload += "&line=" + lineNumber;
    /* submit error message */
    var img = new Image( );
    img.src = "http://example.com/errormonitor.php"+"?error=scriptruntime&"+payload;
    alert("JavaScript Error - Administrators have been notified.");
    /* return true to suppress normal JS errors */
    return true;
}

Please note that we opted not to use an XHR in our code example, but instead invoked an image to issue our request. This is because when errors occur it might just be because something that isn't XHR-aware is running our script!