Reputation: 401
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.
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
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
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