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:
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.