jQuery Error Management Examples

Sam Deering
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:

Frequently Asked Questions (FAQs) on jQuery Error Management

How can I handle errors in jQuery using the .error() method?

The .error() method in jQuery is a powerful tool for handling errors. It binds an event handler to the “error” JavaScript event. This method can be particularly useful when dealing with image loading errors. However, it’s important to note that this method has been removed in jQuery 3.0 and is only available in older versions. For newer versions, you can use the .on() method to bind an error event.

What is the role of the .ajaxError() method in jQuery error management?

The .ajaxError() method is an event handler that is called when an Ajax request completes with an error. It can be attached to any element, but it’s typically attached to the document. This method can be very useful in global error handling. You can use it to display a message when an Ajax request fails, for example.

How can I use the try-catch statement for error handling in jQuery?

The try-catch statement is a JavaScript feature that can also be used in jQuery for error handling. You can use it to “try” a block of code and “catch” any errors that occur. This can be particularly useful when dealing with unpredictable code that may throw exceptions. Here’s a basic example:

try {
// Code to try
} catch (error) {
// Code to run if an error occurs
}

How can I handle specific Ajax errors in jQuery?

jQuery’s .ajax() method provides a way to handle specific Ajax errors. You can use the statusCode option to define callback functions for specific HTTP status codes. For example, you could define a callback for the 404 status code (Not Found) like this:

$.ajax({
statusCode: {
404: function() {
alert('Page not found');
}
}
});

How can I use the .fail() method for error handling in jQuery?

The .fail() method is a callback function that is executed when a Deferred object is rejected. It’s often used in conjunction with the .ajax() method to handle errors. Here’s a basic example:

$.ajax({
// Ajax options
}).fail(function() {
// Code to run if the request fails
});

What is the difference between .error() and .fail() in jQuery?

The .error() method is an event handler that is called when an error occurs, while the .fail() method is a callback function that is called when a Deferred object is rejected. The .error() method is typically used for handling image loading errors, while the .fail() method is often used for handling Ajax errors.

How can I use the .done() and .always() methods in jQuery error management?

The .done() and .always() methods are callback functions that are executed when a Deferred object is resolved or rejected. The .done() method is called when the Deferred object is resolved (i.e., when the operation was successful), while the .always() method is called regardless of whether the Deferred object was resolved or rejected. These methods can be used in conjunction with the .ajax() method to handle success and error scenarios.

How can I handle parse errors in jQuery?

Parse errors in jQuery typically occur when you’re trying to parse invalid JSON data. You can handle these errors by using the try-catch statement. Here’s a basic example:

try {
var data = $.parseJSON(response);
} catch (error) {
// Code to run if a parse error occurs
}

How can I handle timeout errors in jQuery?

Timeout errors in jQuery can be handled by using the timeout option in the .ajax() method. This option sets a timeout (in milliseconds) for the request. If the request takes longer than this time, it’s aborted and the .fail() method is called. Here’s a basic example:

$.ajax({
timeout: 5000, // 5 seconds
// Other Ajax options
}).fail(function() {
// Code to run if a timeout occurs
});

How can I handle errors in jQuery plugins?

Error handling in jQuery plugins can be a bit tricky because it depends on the specific plugin. However, a general approach is to use the try-catch statement to catch any errors that occur in the plugin’s code. You can also use the .error() or .fail() methods if the plugin uses Ajax or Deferred objects.