首页 > 解决方案 > 捕获 Javascript 类方法中的所有异常

问题描述

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

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

并处理此类本地的异常?

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

标签: javascript

解决方案


一种不重复每个方法的方法是让构造函数返回一个代理,当访问一个方法时,返回用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();

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


推荐阅读