0

I am very new to js. I want to insert values into my error table, such as timestamp and type of error returned in node js. My current node js code inserts values into database but I want something in error block. Below is my node.js code.

var pg = require('pg');
var transaction = require('pg-transaction');
var die = function(err){
  if (err) throw err;
};
exports.handler = function(event, context) {
  var pgClient = new pg.Client({
    user: 'XXXX',
    database: 'XXXX',
    password: 'XXXX',
    port: 5439,
    host: "XXXXX"
  });
    pgClient.connect();
    var tx = new transaction(pgClient);
    tx.on('error',die);
    tx.begin();
    tx.query("truncate table tbl;");
    tx.query("insert into tbl..................;");
    tx.query("select * from tbl",function(err,result) {
      console.log("XXXX: "+JSON.stringify(result));
    });
    tx.query("truncate table;");
    tx.commit(function(){

      pgClient.end(function(err) {
        if(err) throw err;
        console.log("Successful");
      });
    });  
};


Insert into error_log(select getdate(),error_type);
So, where do I write my sql?

1 Answer 1

1

Doing it properly, via pg-promise, with an automatic transaction:

const pgp = require('pg-promise')(/*initialization options*/);

const db = pgp({
    user: 'XXXX',
    database: 'XXXX',
    password: 'XXXX',
    port: 5439,
    host: "XXXXX"
});

exports.handler = (event, context) => {
    db.tx(t => {
        return t.batch([
            t.none('truncate table tbl'),
            t.none('insert into tbl..................'),
            t.any('select * from tbl'),
            t.none('truncate table tbl')
        ]);
    })
        .then(data => {
            console.log("XXXX: ", JSON.stringify(data[2]));
        })
        .catch(error => {
            console.log(error);
        });
};
Sign up to request clarification or add additional context in comments.

2 Comments

I just wanted to write to my table whenever there is an error. Not sure where do I write my error handling sql
@RedshiftGuy You have the generic error handler here, for any error. And you didn't specify which specific error, if any you want to handle.

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.