发现错误后如何继续运行脚本?

时间:2019-07-04 10:58:44

标签: node.js mongodb

我正在尝试监视mongo数据库,如果我的脚本失去连接,则服务器需要我发送电子邮件。但是到目前为止,在代码中,我发现了错误并杀死了脚本。

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://server:port/";

async function admin() {
    try {
        const client = MongoClient.connect(url, { useNewUrlParser: true })

        if (!client) {
            // Send email
        }
    } catch(err) {
        if(err == "MongoNetworkError") {
            console.log("no connection")
            send_email_function(); //this function does not run in the case of no connection           
             }

        console.log(err)
        // Send email
    }
}

admin();

1 个答案:

答案 0 :(得分:0)

trycatch无法捕获异步引发的错误。简化的版本可能类似于:

try { setTimeout(() => { throw new Error("I won't be caught") }, 10) }
catch (ex) { // this won't work }

您将要在连接上注册一个侦听器,并在创建初始连接时使用await

let client;
try {
  client = await MongoClient.connect(url, { useNewUrlParser: true });
  client.on("error", (err) => handleError(err));
} catch (err) {
  handleError(err)
}