简体   繁体   English

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

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

Is it possible to use a Proxy to wrap calls to async methods on an object with error handling?是否可以使用代理来包装对具有错误处理的对象上的异步方法的调用?

I tried the code below, but the catch isn't executing when errors are occurring in the proxied method.我尝试了下面的代码,但是当代理方法中发生错误时,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)
        }
    }
})

My goal was to avoid implementing error-handling in each proxied method.我的目标是避免在每个代理方法中实现错误处理。

I tried an approach inspired by Dr. Axel (suggested by Bergi in the question comments), and it works as desired:我尝试了一种受 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()

Output of the above script:上述脚本的输出:

Caught:
Boom!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM