如何使用try/catch块进行mongoDB连接



我想检查到与我的mongodb的连接,如果下降,我想给自己发送电子邮件。我似乎无法掌握我想做的事情的尝试/捕获元素 - 我对JavaScript是新手。

这是我到目前为止的代码:

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://myserver:port/";
function check() {
    MongoClient.connect(url, {useNewUrlParser: true}, async (err, db) => {
            if (err) throw err;
            console.log(err)
        try {
            if(err == "MongoNetworkError") throw "No connection"
        }
        catch(err) {
            console.log("no connection")
        }
})
}

建立连接时,它会打印null,当我通过关闭服务器触发错误时,它不会打印"no connection"

感谢您的任何帮助

连接期间出现错误时,您将具有err != null。这告诉您存在连接错误,您可以在此处发送电子邮件。

您不需要自定义的trycatch块。

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://myserver:port/";
function check() {
    MongoClient.connect(url, {useNewUrlParser: true}, async (err, db) => {
            if (err) { //enter here whenever there is error
              console.log(err) // this gives you more information about the connection error
              if(err instanceof MongoClient.MongoNetworkError) {
                 console.log("no connection") // you can log "no connection" here
                //send email here
              }
            } 
            // go here if no error
    })         
}

由于 MongoClient.connect返回承诺,因此您可以使用async/await检查任何错误以及从连接返回的客户端:

async function check() {
    try {
        const client = await MongoClient.connect(url, { useNewUrlParser: true })
        if (!client) {
            // Send email
        }
    } catch(err) {
        if(err == "MongoNetworkError") {
            console.log("no connection")
        }
        console.log(err)
        // Send email
    }
}
check()

最新更新