我的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
被破坏了。)
我在做什么错了?
答案 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。