有没有办法捕获Javascript类方法中的所有异常?
class Foo {
method1() {}
method2() {}
methodToCatchAllError() {}
}
并处理此类的本地异常?
以类似的方式rescue_from
在Ruby中工作
一种无需对每个方法重复进行操作的方法是让构造函数返回Proxy,并且在访问方法时,返回包装在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();
尽管如此,这还是很奇怪,而且代理很慢。我不推荐它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句