Reputation: 15992
How can i ensure that only error messages that i create are sent to the client, in the context of a promise rejection?
I'm throwing a custom error, which is working fine.
return db.query(`SELECT * FROM events WHERE hostId = ? AND status = ?;`,[userId, ACTIVE_EVENT])
.then((results)=>{
if(results.length != 0)
throw new Error('You already have an active event')
})
It's later being caught
.catch(function (err) {
console.log(err)
res.status(400).send(err.message)
});
And a nice error msg goes to the client.
But sometimes i get a nasty error from a malformed database query, or whatever, and the client would see a msg like "ER_TRUNCATED_WRONG_VALUE: Incorrect time value:"
Upvotes: 5
Views: 4566
Reputation: 3302
You could introduce your custom error object, like this guy did: Node.js custom error handling
Then throw instances of your custom error when needed. And only add the message to the response if the error is an instance of your custom error.
e.g.
.catch(function (err) {
console.log(err)
if (err instanceof CustomError) {
res.status(400).send(err.message)
}
});
Upvotes: 2