5

Let's say if I have a class

class Foo {
  doSomething() { throw 'error'; }
  doOtherthing() { throw 'error2'; }
  handleError(e) {}
}

Is there any implementation to automatically intercept/catch any error that happens in this class and redirect it to an error handling method, in this case handleError()

e.g

const foo = new Foo()
foo.doSomething() 

That should trigger errorHandler(). Angular has such implementation and I am not sure how it got done.

Ayan Sengupta
  • 5,238
  • 2
  • 28
  • 40
Fan Cheung
  • 10,745
  • 3
  • 17
  • 39
  • 1
    No Javascript classes do no have a generic handleError method. *Angular has such implementation* angular is a framework not a language. – Liam Oct 19 '20 at 09:06
  • Then if I want make a framework with this capability what's the suggestion? – Fan Cheung Oct 19 '20 at 09:09
  • Yes you could do this. If you want to know how, well that very much depends on what this "framework" is, what it does and how it work. Ultimately this is as simple as adding a `try {} catch{}` at the top level – Liam Oct 19 '20 at 09:10
  • any implementation direction you can suggest? In angular any error happens in it framework can be caught with a registered ErrorHandler. To my understanding try catch maybe will work for initialization. What about other method calls happen post initialisations. There should be a pattern written to enable this. – Fan Cheung Oct 19 '20 at 09:13
  • We already got a quite legitimate answer here – Fan Cheung Oct 21 '20 at 14:17

1 Answers1

5

You can wrap every method inside an error-handling wrapper systematically:

for (const name of Object.getOwnPropertyNames(Foo.prototype))
  const method = Foo.prototype[name];
  if (typeof method != 'function') continue;
  if (name == 'handleError') continue;
  Foo.prototype.name = function(...args) {
    try {
      return method.apply(this, args);
    } catch(err) {
      return this.handleError(err, name, args);
    }
  };
}

Notice this means that handleError should either re-throw the exception or be able to return a result for all methods of the class (which can be undefined of course).

For asynchronous methods, you'd check whether the return value is a promise and then attach an error handler with .catch() before returning it.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375