是否可以使用代理来包装带有错误处理的异步方法调用?

Is it possible to use a Proxy to wrap async method calls with error handling?

是否可以使用 Proxy 将对异步方法的调用包装在具有错误处理的对象上?

我尝试了下面的代码,但是当代理方法发生错误时,catch 没有执行。

const implementation = {
    // proxied async methods here
}
const proxy = new Proxy(implementation, {
    get: (target, prop, reciever) => {
        try {
            return Reflect.get(target, prop, reciever)
        }
        catch (error) {
            console.log('Error:')
            console.error(error)
        }
    }
})

我的目标是避免在每个代理方法中实施错误处理。

我尝试了 an approach inspired by Dr. Axel(由 Bergi 在问题评论中建议),并且效果如愿:

const object = {
  async foo() {
    return new Promise((resolve, reject) => { reject('Boom!') })
  }
}

function interceptMethodCalls(obj) {
  const handler = {
    get(target, propKey, receiver) {
      const origMethod = target[propKey];

      return async function (...args) {
        try {
          return await origMethod.apply(this, args);
        }
        catch (error) {
          console.log('Caught:')
          console.error(error)
        }
      }
    }
  }

  return new Proxy(obj, handler);
}

const proxy = interceptMethodCalls(object);
proxy.foo()

以上脚本的输出:

Caught:
Boom!