1

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?

2 Answers 2

2

You can add an error event handler on the query object to catch errors during query execution:

query.on('error', function(err) {
  console.log('Query error: ' + err);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Function client.query takes three parameters: (query, params, function (err, result){}).

The third one gives you a callback to provide the error context during the query execution, plus the result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.