简体   繁体   中英

Catch SQL error in Node.js

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?

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);
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM