如何使用如下方法实现类?

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中包装所有类(class)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48696678/

10-09 18:13