nodejs-猫鼬不会因Uri损坏而引发错误

时间:2019-04-16 18:47:31

标签: javascript node.js mongoose

我的index.ts文件中包含以下代码:

import mongoose from 'mongoose'

const DBUri = "blah";

const connectDatabase = (): void => {
    try {
        mongoose.connect(DBUri, {useNewUrlParser: true}, () => {
            console.log('mongoose connected.')
        })
    } catch (e) {
        console.log(e);
        throw e
    }
};

connectDatabase()

当我编译成js并执行文件时,我将mongoose connected登录到控制台。但我希望会引发错误(因为DBUri被破坏了。)

我在做什么错了?

2 个答案:

答案 0 :(得分:1)

通过这些事件,您将发现错误或断开连接

try {
      mongoose.connect(DBUri, {useNewUrlParser: true}, () => {
          console.log('mongoose connected.')
      })

       mongoose.connection.on('disconnected', () => { console.log("Disconnect")  });

       mongoose.connection.on('error', (error) => {
       console.error('[error]: ', error);
      });
    } catch (e) {
    console.log(e);
    throw e
   }

答案 1 :(得分:0)

根据Mongoose文档,您应该在回调中捕获error参数:

mongoose.connect(DBUri, {useNewUrlParser: true}, (err) => {
  if(err) return console.log('mongoose failed to connect.')
  console.log('mongoose connected.')
});

此外,您的try..catch是多余的,因为您已经通过该回调将错误处理传递给Mongoose。

https://mongoosejs.com/docs/connections.html#callback