skip to Main Content

I’m having an issue with one of my AWS Lambda Node JS functions when I call the function from axios in my Next JS frontend. The first time the function is called, it is successful and returns correctly but when I call it again, it returns ‘Error: Runtime exited with error: exit status 128’ and ‘ERROR Unhandled Promise Rejection Runtime.UnhandledPromiseRejection’. When I call it again after a failed attempt, it runs successfully and returns correctly. Is there an issue with my code (below)? I’ve got context.callbackWaitsForEmptyEventLoop set to false but I can’t see why the function fails with rapid fire calls. Thanks in advance

const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectId;

const MONGODB_URI = process.env.MONGODB_URI;

let cachedDb = null;

async function connectToDatabase() {
  if (cachedDb) {
    return cachedDb;
  }

  const client = await MongoClient.connect(MONGODB_URI);

  const db = await client.db(process.env.MONGODB_NAME);

  cachedDb = db;
  return db;
}

exports.handler = async (event, context) => {
  console.log(event.queryStringParameters);
  console.log(event.body);
  let docType = event.queryStringParameters.docType;
  let docId = event.queryStringParameters.docId;
  const bodyData = JSON.parse(event.body);
  let fundId = event.queryStringParameters.fundId;

  context.callbackWaitsForEmptyEventLoop = false;

  const db = await connectToDatabase();

  try {
  const data = await db.collection(docType).findOneAndUpdate({_id : ObjectId(docId), "profile_subscription_documents.fund_id" : fundId},{
    $push: {"profile_subscription_documents.$[psd].profile_fund_subscription_documents": {...bodyData} }
  },
  {
    arrayFilters: [
      {
        "psd.fund_id": fundId
      }]
  },
  {
    returnDocument: "after"
  });
  
  console.log("Here", data);

  const response = {
    statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "*",
            "Access-Control-Allow-Origin": "http://localhost:3000/",
            "Access-Control-Allow-Methods": "*"
        },
    body: JSON.stringify(data),
  };

  return response;
  } catch (error) {
    console.error(error);
  }
  
};

2

Answers


  1. Chosen as BEST ANSWER

    Found the problem to this: the console.log("Here", data); line was returning undefined which I'm guessing meant the function wasn't completing properly. By trial and error I figured that it was the returnDocument: "after" which was causing the issue so I removed that part and now the 'ERROR Unhandled Promise Rejection Runtime.UnhandledPromiseRejection' error has gone and everything is working smoothly!


  2. The first thing that comes to mind is that the connections to the db are not being closed.

    I would add a finally statement closing the db connection like:

      ...
      return response;
      } catch (error) {
        console.error(error);
      } finally {
        db.close();
      }
      ...
    

    I got this suggestion from the MongoDB package docs: https://www.npmjs.com/package/mongodb

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search