Fan Cheung
Fan Cheung

Reputation: 11380

How to intercept all errors in a class instance?

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.

Upvotes: 5

Views: 891

Answers (1)

Bergi
Bergi

Reputation: 665455

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.

Upvotes: 5

Related Questions