javascript - 捕获 Javascript 类方法中的所有异常
问题描述
有没有办法在 Javascript 类方法中捕获所有异常?
class Foo {
method1() {}
method2() {}
methodToCatchAllError() {}
}
并处理此类本地的异常?
以类似的方式rescue_from
在 Ruby 中工作
解决方案
一种不重复每个方法的方法是让构造函数返回一个代理,当访问一个方法时,返回用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();
尽管如此,这还是很奇怪,而且代理很慢。我不会推荐它。
推荐阅读
- r - 在 R ggalluvial 中使用冲积层可视化排名变化
- android - 具有 3 行的 TextView 具有不同的高度,具体取决于填充行的数量
- flutter - 使用 JsonSerialzable 时如何避免 Flutter 中的重复
- javascript - Flashing buttons timing
- reactjs - 如何使全尺寸图像像地图一样水平和垂直滚动
- java - 这些实例化之间有什么区别?
- serverless - 角色无效或无法在 sls deploy 上担任
- php - 如何在while循环之外获取while循环的值?
- ruby-on-rails - 活动管理员 - 在集合操作中使用控制器方法
- r - R bootstrapping 重采样,每个 id 有多个观察值,并返回重采样数据作为结果