I
I
Ivan Pavlenko2019-05-03 21:41:12
MySQL
Ivan Pavlenko, 2019-05-03 21:41:12

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.")
    }
  })

})

Crashes with the following error.
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)

Rummaged everything that could be rummaged through, nowhere is there anything on this topic.
How to be, how to properly handle errors in mysql queries?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
h0w4rd, 2019-05-04
@h0w4rd

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 question

Ask a Question

731 491 924 answers to any question