1
What is the correct method to separate errors from a query?
The current code compares the error manually with the message generated by mysql, in case the query may go wrong for several reasons, instead of returning a log and error 500 like this :
{
err: 'ER_DUP_ENTRY',
code: 500
}
return an error like this :
{
msg: 'Username already in use',
code: 500,
};
Detail :
mysql driver: mysql2
sample code :
const register = async (username, password) => {
try {
const hashedPassword = await bcrypt.hash(password,12);
const user = {
username,
password: hashedPassword
};
await db.query(queryRegister, user);
return {
msg: 'User registered with success',
code: 200,
};
} catch(err) {
if(err.code === 'ER_DUP_ENTRY') {
return {
msg: 'Username already in use',
code: 500,
};
}
}
}