top button
Flag Notify
Site Registration

Exception handling in Jquery

+1 vote
328 views

I am making an Ajax call using Jquery. Sometimes I get error/exception from the back-end. I want to catch them show appropriate error message to the user.

How can I handle exception/error scenarios with Jquery?

posted Mar 25, 2013 by Sudheendra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

The code looks a little something like this:

$.get('url', function() {
    alert("success");
})
.error(function() {
    alert("error");
})

Another snazzy way of dealing with error handling

$.get("url")
.done(function(){ 
    alert("success");
})
.fail(function(){
    alert("error(fail)");
});

You could also use the .ajaxError() method, which involves too much prep work for my taste.

.ajaxError() example:

$(document).ajaxError(function(e, xhr, settings, exception) { 
    alert("error"); 
});

I find that the $.get().error() chaining method is more efficient as it involves the least amount of lines of code. And when you’re working with the mobile web, every line counts.

answer Mar 25, 2013 by Nora Jones
...