简体   繁体   English

在Node.js中捕获SQL错误

[英]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: 我已将pSQL表设置为对某些数据要求唯一值,并调用此函数来插入此数据:

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: 我从具有node.js / express的终结点调用此方法:

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. 当键是唯一的时,这可以很好地工作,但是当测试条件不是唯一的键时,它可以正常工作,并且可以使服务器崩溃,而不是被if (err)块捕获的错误。

What would be the proper way to handle such an occurrence? 处理此类事件的正确方法是什么? Is there a way to do it in the SQL? 有没有办法在SQL中做到这一点?

You can add an error event handler on the query object to catch errors during query execution: 您可以在查询对象上添加error事件处理程序,以在查询执行期间捕获错误:

query.on('error', function(err) {
  console.log('Query error: ' + err);
});

Function client.query takes three parameters: (query, params, function (err, result){}) . 函数client.query具有三个参数:( (query, params, function (err, result){})

The third one gives you a callback to provide the error context during the query execution, plus the result. 第三个给您回调,以提供查询执行期间的错误上下文以及结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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