0

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Is the exception happening when random.js first loads or when some function in it is called later by main.js? FYI, all scripts in the browser run on the client-side so all errors in them are already on the client side so you can't "keep it from reaching the client side". – jfriend00 Feb 23 '15 at 07:10
  • random.js generates error when it gets executed. and by reaching client side i meant showing error to client in console.. i just dont want client to know that an error occured. – Manish Dsouza Feb 23 '15 at 07:18
  • By executed do you mean on load by the browser or when you call a function? – Nick Dickinson-Wilde Feb 23 '15 at 07:19

1 Answers1

0

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).

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • @ManishDsouza - Since it looks like you are perhaps new to StackOverflow, are you aware that if you get your question answered, then you should select the best answer and click the green checkmark to the left of the answer. This will inform the community that your question has been answered and earn both you and the person supplying the answer with some reputation points. – jfriend00 Feb 27 '15 at 04:20