0

I am facing trouble when I try to throw an Error (to mark if there are no username) inside pool query. What I am expect is the error was catch by checkUsername and make it standard json response. But, I always get an error like this:

error details

Here is my code in controller:

const checkUsername = (req, res) => {
  const service = new AuthService()
  try {
    service.chekcUsernameIsExist(req.body.username, res)

    return res.status(200).send('Username is exist')
  } catch (error) {
    const response = {
      status: false,
      message: error.message,
      error_code: 400
    }
    return res.status(400).send(response)
  }
}

And here is my code in service:

class AuthService {
  chekcUsernameIsExist (username) {
    const query = `select * from admins where username = '${username}';`

    pool.query(query, (err, results, release) => {
      if (err) {
        throw err
      } else if (results.rowCount !== 0) {
        console.log('Username is exist')
      } else {
        console.log('Username is not exist')
        throw new Error('Username is not exist')
      }
    })
  }
}

I try to add try catch block inside checkUsernameIsExist but still got the same problem. At the stupid, I add a variable to which have value 1, 2, or 3 to mark is username exist, not exist, or other error.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Wildanzr
  • 1
  • 1
  • 4
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – jonrsharpe Mar 24 '22 at 08:20
  • But note if you _don't_ pass a callback the query method returns a promise instead, which is much easier to deal with. – jonrsharpe Mar 24 '22 at 08:21
  • thank you for giving me insight about asynchronous. I will try to apply it. – Wildanzr Mar 24 '22 at 08:29

0 Answers0