如何使用如下方法实现一个类?
class ExistingClass {
function func1() {} // might throw error
function func2() {} // might throw error
get try() {
// Some magic here
return this; // we need to return this to chain the calls, right?
}
}
并且可以这样调用
obj.func1() //might throw an error
obj.try.func1() // execute func1 in a try/catch
基本上我想要像mochajs那样的东西:expect(..).to.not.equal()
更新:
接受的答案应该有效,以下是它的更新版本,支持 async
功能
get try() {
return new Proxy(this, {
// Intercept method getter
get: function(target, name) {
if (typeof target[name] === 'function') {
if (target[name][Symbol.toStringTag] === 'AsyncFunction') {
return async function() {
try {
await target[name].apply(target, arguments);
}
catch (e) {}
}
} else {
return function() {
try {
return target[name].apply(target, arguments)
}
catch (e) {}
}
}
}
return target[name];
}
});
}
最佳答案
elclanrs's solution 的简化版本
class A {
method() {
throw 'Error';
}
get try() {
return new Proxy(this, {
// Intercept method getter
get(target, name) {
if (typeof target[name] === 'function') {
return function () {
try {
return target[name].apply(target, arguments)
} catch (e) {}
}
}
return target[name];
}
});
}
}
const a = new A;
a.try.method(); // no error
a.method(); // throws error
关于javascript - 将所有类都封装在 try/catch javascript 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48696678/