-1

Is it possible to catch undefined reference in global (window) scope is browser and require function instead of throwing error and without wrapping all functions in try-catch?

Example. I have function

$('#id').on('click', function(){
    a();
})

If a function is not defined, I just get an error Uncaught ReferenceError: a is not defined

What I want - is to define some global function that will catch all such errors, and require needed file (based on a map) instead of throwing errors.

I know it's possible in nodejs to catch any error, but is it possible in browser?

Denis Matafonov
  • 2,684
  • 23
  • 30
  • 1
    "*require needed file based on the error*" - that's the wrong approach. You should declare your dependencies explicitly, instead of trying to load them after they failed you. Which of course isn't going to work anyway, as neither is loading synchronous nor will the handler be able to recover from the error. You might just as well use [Vigil](https://github.com/munificent/vigil). – Bergi Feb 12 '16 at 14:55
  • You might be looking for `window.onerror`, see the possible duplicate [Javascript global error handling](http://stackoverflow.com/q/951791/1048572) – Bergi Feb 12 '16 at 14:58

2 Answers2

1

Can't you just check the type?

if (typeof a !== 'undefined') {
   //execute the function
   a();
} else {
   //do something else
   console.log('not defined'); 
}

I think if (typeof a == 'function') {...}' would be even more explicit.

Here's some more about typeof:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

Marc
  • 11,403
  • 2
  • 35
  • 45
0

It is not enough to check simply if exists before calling it?

a && a();
István
  • 5,057
  • 10
  • 38
  • 67