Evening stack! Tonight I decided to play around with some NodeJS and I'm having a little trouble understanding the appropriate way for me to handle errors in this situation.
I have a table that simply stores playerName
and the name must be unique. So rather than just try to insert and get an error, I want to first make a select and if I get a result, return a 400 to the user and let them know the name already exists. If not, continue on as normal, insert the name, and return a 203.
What I've got clearly isn't working. I've attempted a try/catch and that didn't work. And I clearly can't return an error with the methods I'm using. So what's a good way to go about this?
router.post('/addPlayer' , function(req, res, next){
var playerName = req.body.name;
if(playerName === undefined || playerName.length === 0)
{
return res.status(400).send('No name provided');
}
var query = 'SELECT name FROM players WHERE name LIKE ?';
var inserts = [playerName];
query = connection.format(query , inserts);
connection.query(query, function(err, results){
if(err) return res.status(500).send('Error connecting to database.');
if(results.length !== 0) return res.status(400).send('This name has already been used.');
});
query = 'INSERT INTO players (name) VALUES(?)';
inserts = [playerName];
query = connection.format(query , inserts);
connection.query(query, function(err){
if(err) return res.status(500).send('Error connecting to database.');
});
res.status(201).send("Added player: " + playerName);
});
In this current version my obvious problem is Node crashes complaining about not being able to set the headers after they've already been sent. I know what I need to do. Which is end the execution of the route and return the error to the browser, but I'm just not clear on how to best go about that.
I'm using the Express framework and mysql.
Thanks.