jQuery Error Management Examples

Sam Deering
Share

error-management2-basics

Ok, so I’m assuming you all know about Firebug and FireQuery. If you don’t these posts may help you. Firebug has a number of powerful tools that can make the previous nightmare of JavaScript debugging tolerable.

So now you want to manage those errors better not just so that your users don’t see any errors but to also help when you are developing your scripts.

Alert()

javascript-error-alert

//alert() shows values in a popup window
alert("js is working");

Alert can be used to see if your code is actually be executed because if there are critical syntax errors in your JavaScript it won’t execute at all. Can also be used to see if a certain code block or segment is being reached.

Console.log()

javascript-error-console-log

//console.log() shows values in the firebug console window
var x = ... etc
console.log(x);

Console.log() can be very useful for showing values executed in loops and for catching events. More on this later in the post. The full range of options for logging can be seen in the Firebug Console API wiki page.

Important: make sure you enclose your firebug commands otherwise your jQuery code will only work when the console is open.

Try/Catch

//try catch example 1
try {
	$("#user").focus();
} catch(err){
	return false;
}

//try catch example 2
try {
var tmp = doSomething();
if (tmp == something.errorCondition)
throw new Error("Error condition in X");
} catch(err) {
//handle ((err && err.message) || err.toString())
} 

//try catch example 3
try {
  // code that may cause an error
} catch (e) {
  // deal with error (or not)
}
// code that runs whether or not error occurred

Override Errors for display in Firebug

You can also override jQuery.error for display in Firebug like so:

jQuery.error = console.error;

jQuery Stop Error Display

If you use jQuery event handlers, you can use a combination of window.onerror and wrapping the jQuery event handler code and on ready function with an error handling function.

  • window.onerror: catches all errors in IE (and most errors in Firefox), but does nothing in Safari and Opera.
  • jQuery event handlers: catches jQuery event errors in all browsers.
  • jQuery ready function: catches initialisation errors in all browsers.

Types of jQuery Errors (common errors)

A common error is when AJAX returns no data. This can be handled by adding error messages, see the following example of an AJAX contact form.

$("#createContact").click(function () { //Attach a click event handler to the button
    var form = $("form"); //Grab the form element from the DOM

    $.ajax({
        type: "POST", //The type of HTTP verb (post, get, etc)
        url: form.attr( "action" ), //The URL from the form element where the AJAX request will be sent
        data: form.serialize(), //All the data from the form serialized
        dataType: "json", //The type of response to expect from the server
        success: function ( data, statusCode, xhr ) { //Triggered after a successful response from server
            if ( data && data.Message ) {
            	alert( data.Message );
            }
        },
        error: function ( xhr, errorType, exception ) { //Triggered if an error communicating with server
            var errorMessage = exception || xhr.statusText; //If exception null, then default to xhr.statusText

            alert( "There was an error creating your contact: " + errorMessage );
        }
    });

    return false; //Ignore the default behavior of the button click
});
[code lang="php"]

Checking in firebug the has a StatusText field which can be used to determine the type of jQuery error.

firebug-error-management

Useful AJAX Catch Error Function

function ajaxError(request, type, errorThrown)
{
	var message = "There was an error with the AJAX request.n";
	switch (type) {
		case 'timeout':
			message += "The request timed out.";
			break;
		case 'notmodified':
			message += "The request was not modified but was not retrieved from the cache.";
			break;
		case 'parseerror':
			message += "XML/Json format is bad.";
			break;
		default:
			message += "HTTP Error (" + request.status + " " + request.statusText + ").";
	}
	message += "n";
	alert(message);
}

Further reading: