I have a pSQL table set to require unique values for some data, and I call to insert this data with the function:
CREATE OR REPLACE FUNCTION create_location(
name text,
latitude numeric,
longitude numeric,
logo_url text = '')
RETURNS void AS $$
INSERT INTO "PartySpot".locations (name, latitude, longitude, logo_url)
VALUES (name, latitude, longitude, logo_url);
$$ LANGUAGE SQL VOLATILE STRICT;
I call this from an endpoint with node.js/express with:
pg.connect(connectionString, function(err, client, done) {
var query = client.query("SELECT * FROM create_location($1,$2,$3,$4)",
[req.body.name,
req.body.latitude,
req.body.longitude,
req.body.logo_url]
);
query.on('row', function(row) {
results.push(row);
});
query.on('end', function(row) {
client.end();
return res.json(results);
});
if(err) {
console.log(err);
}
});
This works fine when the key is unique, but when testing the condition where it isn't, instead of the error being caught by the if (err) block, it goes unhanded and crashes the server.
What would be the proper way to handle such an occurrence? Is there a way to do it in the SQL?