AWS Lambda returns internal server error while returning response from a recursive callback function

Consider this example from docs for Amazon DynamoDB, here we have:

dynamoDb.scan(params, onScan);

function onScan(err, data) {
      if (err) {
          return;
      } else {
        collectedItems.push(data.Items);

        const response = {
          statusCode: 200,
          headers: {
            'Access-Control-Allow-Origin': '*',
          },
          body: JSON.stringify(collectedItems),
        };
        callback(null, response);

        // continue scanning if we have more movies, because
        // scan can retrieve a maximum of 1MB of data
        if (typeof data.LastEvaluatedKey != "undefined") {
            console.log("Scanning for more...");
            params.ExclusiveStartKey = data.LastEvaluatedKey;
            dynamoDb.scan(params, onScan);
        }



      }
  }

that should show me collectedItems as json response for API Gateway. But it returns

{
 message: "Internal server error"
}

You would need to post you’re entire handler if you want help debugging this. From what you’ve posted I can see two problems

  1. You’re using callback to return a result before you call scan to begin the recursion.
  2. You’re not sending a response if an error occurs

Personally I wouldn’t waste my time trying to get recursive callbacks working. Switch your run time to Node 8.10 and take advantage of async/await so your code is easier to read.