A
A
Artem Lukyanov2019-10-06 18:25:26
Node.js
Artem Lukyanov, 2019-10-06 18:25:26

Try catch or then catch for rest api?

There is an api request handler, where db.query() is a request to PostgreSQL, which returns a Promise with resolve on success, and reject on error (for example, if the database password is wrong).
The request handler itself:

async getAll(req, res) {
    const query = `SELECT * FROM users`
    return db
      .query(query)
      .then(({ rows, rowCount }) => res.status(200).send({ rows, rowCount }))
      .catch(error => res.status(400).send({ error }))
    // try {
    //   const { rows, rowCount } = await db.query(query)
    //   return res.status(200).send({ rows, rowCount })
    // } catch (error) {
    //   return res.status(400).send(error)
    // }
  }

Accordingly, the question is, how best to handle the promise, through try catch or then catch ? I read on stackoverflow that try catch is better to use for synchronous actions, and then catch for asynchronous ones? Is it so?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question