Reputation: 39
Consider a case where I am working with for example the script main.js.
Now when I include some random.js file in main.js file.
If random.js file generates some error how do I catch and handle it in my main.js file so that it does not reaches the client side.
Upvotes: 0
Views: 1891
Reputation: 707556
When an external script (e.g. one that loads from its own script tag) first initializes, if it throws an exception, there is no way to catch that exception directly and handle it from outside that script.
If you can modify that script, then you can put an exception handler around the initialization code and catch the error there.
Inside of random.js
:
try {
// initialization code in random.js
} catch(e) {
// code to handle the exception gracefully here
}
One thing you can do is to hook up a global error handler using:
window.onerror = function(errorMsg, url, lineNumber) { return true; };
If this function returns true
, then it will prevent any default error handling. Details here.
If the problem was occurring when a function in the random.js was called from main.js, then you could put an exception handler in main.js around the function call and catch the exception that way (but it now sounds like this is not your specific case).
Upvotes: 0