is there a mongoose connect error callback

后端 未结 6 1400
别那么骄傲
别那么骄傲 2020-11-30 02:42

how can i set a callback for the error handling if mongoose isn\'t able to connect to my DB?

i know of

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


        
6条回答
  •  旧巷少年郎
    2020-11-30 03:17

    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.

    So, to handle initial connection errors, you should use .catch() or try/catch with async/await.

    In this way, we have two options:

    Using the .catch() method:

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

    or using try/catch:

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

    IMHO, I think that using catch is a cleaner way.

提交回复
热议问题