I have this try-catch block which is supposed to catch any errors encountered while connecting to a Mongo Database, and return the status of "Unauthorised". However, Express crashes in the backend although I am handling the errors if I turn off the MongoDB engine for testing. Shouldn't the errors be handled properly? (I am not using the err code as of now for testing.)
app.post('/api/login', (req, res) => {
id = req.body.account
var query = {_id: id}
try {
db.collection("Users").findOne(query, (err, result) => {
if (result) {
nonce = noncef()
var upvalues = { $set: {nonce: nonce} }
db.collection("Users").updateOne(query, upvalues, (err, result) => {
if (result) {
res.send(`${nonce}`)
}
})
}
})
}
catch(err) {
res.status(401).send('Unauthorized')
}
})
Use Promises for .findOne and .updateOne instead of callbacks, and then you can await the results (and catch them), or chain a .catch onto the Promise chain.
app.post('/api/login', async (req, res) => {
const query = { _id: req.body.account }
try {
const user = await db.collection("Users").findOne(query);
if (!user) return;
const nonce = noncef();
const upvalues = { $set: { nonce } };
const updated = await db.collection("Users").updateOne(query, upvalues);
if (updated) res.send(nonce);
} catch (err) {
res.status(401).send('Unauthorized')
}
})
Generally, in modern JavaScript, you should always be preferring promises to callbacks when possible - promises make chaining and catching asynchronous code much more convenient.