I have the following code:
app.post('/routes/passwordReset/:userId', async (req, res, next) => {
var userId = req.params.userId
let record = (await vars.connection.queryP('SELECT * FROM contacts WHERE id = ?', userId))[0]
if (!record) {
res.status(404).send('')
return
}
// Calculate token and expiry, update database
var token = require('crypto').randomBytes(48).toString('base64').replace(/[^a-zA-Z0-9]/g, '').substr(0, 28)
var now = new Date()
var inOneHour = new Date(now.getTime() + (1 * 1000 * 60 * 60))
await vars.connection.queryP('UPDATE contacts SET recoverToken = ?, recoverTokenExpiry = ? WHERE id = ?', [ token, inOneHour, userId ])
res.status(200).send('')
})
If I create an artificial error (e.g. the field for recoverTokenExpiry
is artificially too short) I end up with:
[[12:19:55.649]] [ERROR] (node:11919) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): Error: ER_DATA_TOO_LONG: Data too long for column 'recoverToken' at row 1
I somehow thought that Express would have try/catch around middleware and called next(err)
if an error was thrown. Maybe not so?
So, should I wrap each route with try/catch(e), doing next(e) if there is an error?
app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!') });
– Himanshu Bansal