Home > Back-end >  MongoClient.connect fails, but does not throw an error
MongoClient.connect fails, but does not throw an error

Time:11-29

  try {
    if (!conn) {
      console.log("Attempting to Connect to Atlas");
      conn = await MongoClient.connect(process.env.MONGO_URL, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      });
      console.log("Successfully connected to Atlas");
    }
  } catch (err) {
    console.log("Failed to connect to Atlas: ", err);
    return {
      statusCode: 500,
      body: JSON.stringify(err),
    };
  }

The above is my code to connect to Atlas via Node. The Atlas database has not enabled the IP address of the above server to connect. Hence it is supposed to fail. But when it does failed, the code in the catch block is not executed, here are the logs:

2022-11-28T14:10:35.966-06:00   2022-11-28T20:10:35.966Z 7e455355-8126-4f71-afb3-2185683f9f8a INFO Attempting to Connect to Atlas

2022-11-28T14:10:38.725-06:00   2022-11-28T20:10:38.725Z 7e455355-8126-4f71-afb3-2185683f9f8a Task timed out after 3.01 seconds

2022-11-28T14:10:38.725-06:00   END RequestId: 7e455355-8126-4f71-afb3-2185683f9f8a

2022-11-28T14:10:38.725-06:00   REPORT RequestId: 7e455355-8126-4f71-afb3-2185683f9f8a Duration: 3008.53 ms Billed Duration: 3000 ms Memory Size: 128 MB Max Memory Used: 49 MB

2022-11-28T14:11:42.725-06:00   START RequestId: 7e455355-8126-4f71-afb3-2185683f9f8a Version: $LATEST

The question is, why doesn't it throw an error? Why doesn't it go into the catch block?

This is a lambada function on AWS attempting to connect to atlas.

CodePudding user response:

By Default MongoDB connection timeout occurs after 30 seconds of initiation.

If you see the logs, task being timed out right after 3secs & you're being billed for 3secs of lambda usage. So, your code is just executing for 3secs & timing out. Try to check & increase timeout of your lambda to a minute & you might see actual DB connection failures.

Ideally, if you're using serverless you can pass timeout as an option or at API gateway level.

  • Related