如何拦截类实例中的所有错误?

Fan*_*ung 5 javascript error-handling

假设我有课

class Foo {
  doSomething() { throw 'error'; }
  doOtherthing() { throw 'error2'; }
  handleError(e) {}
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,是否有任何实现可以自动拦截/捕获此类中发生的任何错误并将其重定向到错误处理方法 handleError()

例如

const foo = new Foo()
foo.doSomething() 
Run Code Online (Sandbox Code Playgroud)

那应该会触发 errorHandler()。Angular 有这样的实现,我不确定它是如何完成的。

Ber*_*rgi 5

您可以系统地每个方法包装在错误处理包装器中:

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);
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

请注意,这意味着handleError应该重新抛出异常或能够为类的所有方法返回结果(undefined当然可以)。

对于异步方法,您将检查返回值是否为承诺,然后.catch()在返回之前附加错误处理程序。