Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would this AWS lambda cause error: WARNING: Callback/response already delivered

  • I created an API Gateway + lambda for signUp with amazon-cognito-identity-js.
  • Then I implemented a Cognito trigger function for preSignUp with Typescript

I use Serverless framework to pack and deploy. The runtime is Node 12

+++++++

  const wrapperHandler: Handler<CognitoUserPoolEvent> = async (
    event,
    context,
    callback
  ) => {
    let error = null;

    try {
      await myAsyncFunc();
    } catch (e) {
      error = e;
    }

    callback(error, event);
  };

Everything works fine, it can return the error to the actual endpoint lambda which will then be returned, if no error, the logic will be executed.

However, this warning is pretty annoying.

The code is for preSignUp in CloudWatch

WARNING: Callback/response already delivered. Did your function invoke the callback and also return a promise? For more details, see: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html

In the code, I didn't return anything before calling the callback, why would this happen? and how to solve it.

like image 867
Albert Gao Avatar asked Jul 21 '26 05:07

Albert Gao


1 Answers

As your error message what did you get, you are mixing callback style with async/await style, then it throws a warning.

I prefer use async/await. This mean, handler function always is a async function (with async keyword), then instead of call callback function, just return the result, and you no need callback parameter in handler function.

In error case, just throw the error (without try/catch block).

const wrapperHandler: Handler<CognitoUserPoolEvent> = async (
  event,
  context,
  // callback
) => {
  // let error = null;

  try {
    await myAsyncFunc();
  } catch (e) {
    // error = e;
    // Do something  with your error
    throw e;
  }

  // callback(error, event);
  return event; // just return result for handler function
};

In simple:

const wrapperHandler: Handler<CognitoUserPoolEvent> = async (
  event,
  context,
) => {
  await myAsyncFunc();

  return event;
};

like image 164
hoangdv Avatar answered Jul 22 '26 19:07

hoangdv