javascripterror-handlingproxy

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.

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.


Solution

  • I tried an approach inspired by Dr. Axel (suggested by Bergi in the question comments), and it works as desired:

    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);
    await proxy.foo()
    

    Output of the above script:

    Caught:
    Boom!