javascripttypescriptaws-lambdadecoratormethod-modifier

How to wrap a function (method) with try-catch in modern javascript using decorators (native)?


how can I do something like:

class LambdaFunctionExample {

  lambdaResponse = [1, 2 , 3]

  @tryCatchWrapper
  async handler(event) {
    const data = this.lambdaResponse;
    const result = await fetch(...)

    return {
      statusCode: 200,
      data,
      result
    };
  }

}

and catch errors/events for POC purposes.


Solution

  • for POC purposes, as mentioned

    I'm using:

    class LambdaFunctionExample {
    
      lambdaResponse = [1, 2, 3]
    
      @tryCatchWrapper
      async handler(event) {
        const data = this.lambdaResponse;
        const result = await fetch(...)
    
        return {
          statusCode: 200,
          data,
          result
        };
      }
    
    }
    
    export const handler =  (event) => new LambdaFunctionExample().handler(event)
    

    decorator function:

    export function tryCatchWrapper<T>(target: Function, { kind, name, ...context }) {
      if (kind === 'method')
        return async function (this: unknown, ...args: any) {
          try {
            console.log('name', name)
            return await target.call(this, ...args)
          } catch (error) {
            console.log('error catched')
            return {}
          }
        }
    }
    

    and running

    npm start # node index.js (as usual)
    

    .tsconfig

      "compilerOptions": {
        // Module Setup
        "target": "ES2022", // as of today, I tried with ESNext and it did't work, so I need to use strictly ES2022
        //"module": "NodeNext", (also optional, but important if you are using ESM)
        //"moduleResolution": "NodeNext", (also optional, but important if you are using ESM)
        ...
      }