捕获 Javascript 类方法中的所有异常

GN.*_*GN. 5 javascript

有没有办法捕获 Javascript 类方法中的所有异常?

class Foo {
  method1() {}
  method2() {}
  methodToCatchAllError() {}
}
Run Code Online (Sandbox Code Playgroud)

并处理该类的本地异常?

rescue_from在 Ruby 中以类似的方式工作

Cer*_*nce 3

一种无需为每个方法重复自己的方法是让构造函数返回一个代理,并且当访问方法时,返回用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();
Run Code Online (Sandbox Code Playgroud)

尽管如此,这还是很奇怪,而且代理速度很慢。我不会推荐它。