Answer the question
In order to leave comments, you need to log in
What is the correct way to throw exceptions in mysql request handler in express.js?
Throwing an exception inside the mysql request handler kicks the express server out.
router.get('/user/:userId', (req, res) => {
// let sid = req.query.sid
const {db} = req.app.locals;
db.query('SELECT * FROM `users` WHERE `id`=' + req.params.userId, (error, results, fields) => {
if (error) {
throw error
}
if (results.length) {
res.send(results)
} else {
throw new Error("User not found.")
}
})
})
D:\Project\vopen\server\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error: User not found.
at Query.db.query (D:\Project\vopen\server\routers\users\index.js:16:11)
at Query.<anonymous> (D:\Project\vopen\server\node_modules\mysql\lib\Connection.js:525:10)
at Query._callback (D:\Project\vopen\server\node_modules\mysql\lib\Connection.js:491:16)
at Query.Sequence.end (D:\Project\vopen\server\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query.ErrorPacket (D:\Project\vopen\server\node_modules\mysql\lib\protocol\sequences\Query.js:90:8)
at Protocol._parsePacket (D:\Project\vopen\server\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (D:\Project\vopen\server\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (D:\Project\vopen\server\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (D:\Project\vopen\server\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (D:\Project\vopen\server\node_modules\mysql\lib\Connection.js:91:28)
Answer the question
In order to leave comments, you need to log in
I support the answer of Anton Shvets, but I want to add:
Still, you shouldn't use "Error" anywhere at all, you should think ten times before using this.
And no less important: you have no protection against SQL injection in your code, let's say an evil user can write instead of "1" 1"; DROP TABLE `users`; --
and the "users" sign will disappear.
So it's better to write:
And don't forget that the request may not contain "userId", because the evil user may want to break the logic... After all, such is life.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question