darga33
darga33

Reputation: 401

How to throw an error inside of a call back, and catch it outside

Intro

Inside of this jQuery(document).ready() function, inside the anonymous function, I am throwing an error which gets caught inside of the second catch block. Then I am throwing an error inside of that catch block AND trying to catch it outside in the first try catch block.

Questions.

  1. Is this possible? BROWSER CONSOLE says "UNCAUGHT."
  2. If so, how is it possible?
  3. Any other info would be greatly appreciated - Trying to wrap my head around this.

    try {
            // bind to ready
            jQuery(document).ready(function () {
                try {
                    throw Error("Can this be caught outside of this jquery callback?");
                    _this.initialize();
                } catch(e) {
                    console.log(e.message + ' Caught inside callback');
                    throw Error(e.message + ' Not caught outside');
                }

            });

        } catch(e) {
            //NEVER gets executed.
            console.log(e.message);
        } 
    

Upvotes: 4

Views: 6840

Answers (2)

Igor
Igor

Reputation: 15893

Event handlers for $(document).ready are executed asynchronously to the code that registers them - if the page is still loading, when the registration occurs. Your function() { ... throw ... } executes outside the outer try/catch block. What you are asking is not possible.


Explanation of behaviour observed by @RickHitchcock in https://jsfiddle.net/a3vttpk6/ (see first comment to the question)

If in Rick's fiddle you click on Javascript settings button, you will see that "LOAD TYPE" setting is "onLoad". This means that the whole js code in this window is wrapped in window.onload = function() { ... }. The consequence of this is - the immediate execution of $(document).ready handlers, because the page has already loaded. If you choose "no wrap" setting - you will see the behaviour described in the question.

Upvotes: 5

SethWhite
SethWhite

Reputation: 1977

let promise = new Promise((resolve, reject) => {
  jQuery(document).ready(() => {
    resolve('documentReady')
  });
})

promise.then((response) => {
  //run code here like you would in the ready callback
  throw Error("Can this be caught outside?");
}).catch(error => console.log(error, 'Caught you!'))

Leveraging promises, we can run a function after the document ready event fires. If there's an error, we can throw an error that the Promise catches. Should work just fine. While not technically catching an error from the ready callback, this has the same functionality.

To divorce it entirely, just assign a variable to promise.then() and reference it with .catch later.

Upvotes: 1

Related Questions