[英]MongoClient.connect fails, but does not throw an error
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.以上是我通过 Node.js 连接到 Atlas 的代码。 The Atlas database has not enabled the IP address of the above server to connect.
Atlas数据库没有开启上述服务器的IP地址连接。 Hence it is supposed to fail.
因此它应该失败。 But when it does failed, the code in the catch block is not executed, here are the logs:
但是当它失败时,catch 块中的代码不会被执行,这里是日志:
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?
为什么它 go 不进入 catch 块?
This is a lambada function on AWS attempting to connect to atlas.这是 AWS 上的一个 lambada function 试图连接到 atlas。
By Default MongoDB
connection timeout occurs after 30 seconds of initiation.默认
MongoDB
连接超时发生在启动 30 秒后。
If you see the logs, task being timed out right after 3secs & you're being billed for 3secs of lambda usage.如果您看到日志,任务在 3 秒后立即超时,并且您需要为 lambda 使用量的 3 秒付费。 So, your code is just executing for 3secs & timing out.
因此,您的代码仅执行 3 秒并超时。 Try to check & increase
timeout
of your lambda to a minute & you might see actual DB connection failures.尝试检查并将 lambda 的
timeout
增加到一分钟,您可能会看到实际的数据库连接失败。
Ideally, if you're using serverless
you can pass timeout
as an option or at API gateway level.理想情况下,如果您使用的是无服务器,则可以将
timeout
作为选项或在serverless
网关级别传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.