Tutorial :Catch exceptions in jQuery



Question:

I have the following code:

<script type="text/javascript">      $(document).ready(function() {            $("#Save").click(function() {                $.post("url", {                  "data": "data"              }, function(data) {                  alert(data);              });            });        });  </script>  

I'm testing this script, and one of the tests I'm making is, I just close the asp.net web development server, and click the button.

IE says "access denied" error, I want to catch any error that occurs here, and display a friendly message to the user in this case.

I trying to use try/catch but didn't work...

Any clue?


Solution:1

Use the $.ajax() method instead. It has a hook for errors.

For example:

$.ajax({      url: 'document.xml',      type: 'GET',      dataType: 'xml',      timeout: 1000,      error: function(){          alert('Error loading XML document');      },      success: function(xml){          // do something with xml      }  });  


Solution:2

This is a useful snippet for tracking down any jquery ajax errors in conjunction with FireBug.

// Displays any ajax errors in the Firebug console instead of hiding them  $(document).ajaxError(function(){      if (window.console && window.console.error) {          console.error(arguments);      }  });  

If you use Ajax with jQuery, you may have noticed that you don't get any error messages when things go wrong. Even if you have major bugs in your callback functions, jQuery just silently fails, sweeping any errors under the rug, and leaving you clueless as to what just happened.

After running this code, you'll start getting error messages in your Firebug console (if anything breaks with your Ajax calls or callbacks). The error messages aren't the greatest, but at least you don't have to stay in the dark any longer.

Credit goes to Jesse Skinner


Solution:3

good, I guess javascript support finally also, like this

try{       main code...  }catch(err){       error ocurred...  }finally{       do this anyway...  }  


Solution:4

put a wrapper around all your js code like this:

           try             {         ... js code                 }           catch(err)          {           alert(err.toString());           }  

But for ajax calls this propably doesn't work.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »