GN.
GN.

Reputation: 9899

Catch all exceptions in Javascript Class methods

Is there a way to catch all exceptions in Javascript Class methods?

class Foo {
  method1() {}
  method2() {}
  methodToCatchAllError() {}
}

And handle the exceptions local to this class?

In the similar way rescue_from works in Ruby

Upvotes: 5

Views: 1505

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371168

One way to do it without repeating yourself for every method would be for the constructor to return a Proxy, and when a method is accessed, return that method wrapped in a try//catch:

const handler = {
  get(target, prop) {
    return !Foo.prototype.hasOwnProperty(prop)
      ? target[prop]
      : function(...args) {
        try {
          target[prop].apply(this, args);
        } catch(e) {
          target.methodToCatchAllError('Error thrown...');
        }
      };
  }
};
class Foo {
  constructor(id) {
    this.id = id;
    return new Proxy(this, handler);
  }
  method1() {
    console.log(this.id);
  }
  method2() {
    throw new Error();
  }
  methodToCatchAllError(error) {
    console.log('Caught:', error);
  }
}

const f = new Foo(5);
f.method1();
f.method2();

Still, this is pretty weird, and Proxies are slow. I wouldn't recommend it.

Upvotes: 3

Related Questions