Catch exceptions in jQuery

15,712

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

Share:
15,712
punit
Author by

punit

Por um mundo sem gambi!

Updated on June 18, 2022

Comments

  • punit
    punit almost 2 years

    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?