I'm new to Node JS, and I'm struggling to handle error properly when using promises. Here is what I currently have:
I have a module call db.js with an init function used to set up and start the db connection:
function initDb(){
return new Promise((resolve, reject) => {
if(database){
console.warn("Trying to init DB again !")
}else{
client.connect(config.db.url, {useNewUrlParser: true, useUnifiedTopology: true})
.then((client) => {
console.log("DB initialized - connected to database: " + config.db.name)
database = client.db(config.db.name)
})
.catch((err) => {
reject(err)
})
}
resolve(database)
})}
This function will return a promise, and it will be called into the index.js:
initDb()
.then(() => {
app.listen(8081, function () {
console.log('App is running on port 8081')
})
})
.catch((error) => {
console.log(error)
})
As you can see I have two catch. One in the db module and the other one in the index.js
It seams weird to catch error in two places... What is the good pattern to use to handle error in this case ?