簡體   English   中英

有沒有 mongoose 連接錯誤回調

[英]is there a mongoose connect error callback

如果 mongoose 無法連接到我的數據庫,我該如何設置錯誤處理回調?

我知道

connection.on('open', function () { ... });

但是有沒有類似的東西

connection.on('error', function (err) { ... });

?

當您連接時,您可以在回調中獲取錯誤:

mongoose.connect('mongodb://localhost/dbname', function(err) {
    if (err) throw err;
});

您可以使用許多 mongoose 回調,

 // CONNECTION EVENTS // When successfully connected mongoose.connection.on('connected', function () { console.log('Mongoose default connection open to ' + dbURI); }); // If the connection throws an error mongoose.connection.on('error',function (err) { console.log('Mongoose default connection error: ' + err); }); // When the connection is disconnected mongoose.connection.on('disconnected', function () { console.log('Mongoose default connection disconnected'); }); // If the Node process ends, close the Mongoose connection process.on('SIGINT', function() { mongoose.connection.close(function () { console.log('Mongoose default connection disconnected through app termination'); process.exit(0); }); });

更多信息: http://theholmesoffice.com/mongoose-connection-best-practice/

如果有人遇到這種情況,我正在運行的 Mongoose 版本(3.4)會按照問題中的說明工作。 所以下面可能會返回錯誤。

connection.on('error', function (err) { ... });

As we can see on the mongoose documentation for Error Handling , since the connect() method returns a Promise, the promise catch is the option to use with a mongoose connection.

因此,要處理初始連接錯誤,您應該使用.catch()try/catchasync/await

這樣,我們有兩種選擇:

使用.catch()方法:

mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true })
.catch(error => console.error(error));

或使用 try/catch:

try {
    await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
    console.error(error);
}

恕我直言,我認為使用catch是一種更清潔的方式。

遲到的答案,但如果你想保持服務器運行,你可以使用這個:

mongoose.connect('mongodb://localhost/dbname',function(err) {
    if (err)
        return console.error(err);
});
  • 處理(捕獲)連接異常
  • 處理其他連接錯誤
  • 成功連接時顯示一條消息
mongoose.connect(
  "mongodb://..."
).catch((e) => {
  console.log("error connecting to mongoose!");
});
mongoose.connection.on("error", (e) => {
  console.log("mongo connect error!");
});
mongoose.connection.on("connected", () => {
  console.log("connected to mongo");
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM