brianc/node-pg-cursor

Error Handling

Digicrat opened this issue · 4 comments

I could be doing something wrong in my error handling, but it appears that pg-cursor doesn't behave nicely if there's an error with the initial query. Specifically, the connection is not freed immediately, or at all. See demo below.

In this particular case it would actually be useful to obtain the error immediately, without waiting for a cursor.read() call. For example, a callback parameter to the Cursor constructor (or the query call) that is called when we know the status of the query, without retrieving any rows.

var pg = require('pg');
var Cursor = require('pg-cursor');
var conString = "postgres://username:password@localhost/database";

pg.connect(conString, function(err, client, done) {
    if (err) {
        return console.error('error fetching client from pool', err);
    }

    var cursor = client.query(new Cursor('SELECT * FROM invalid')); // This query is invalid
    cursor.read(10, function(err, rows) {
        if (err) {
            console.log("Found an error"); // Base Test (never exits)
       /* // ALT Test: If I call done() instead of cursor.close() the script will exit, but only after a 30-second delay (some sort of timeout I'd assume).
            console.log("Found an error, calling done()");
            done();
            return;
        */
        } else {
            console.log("No error");
        }
        // If we reach this point with a cursor.read err, cursor.close's callback will never be called and the script will not exit
        cursor.close(function(err) {
            if (err) {
                console.log("Close Error");
            } else {
                console.log("Close Succeeded, calling done");
                done();
            }
        });
    });

});

The error status isn't returned until the query is dispatched to the backend PostgreSQL server, so I think it makes most sense to return in the read callback.

@brianc I broke an existing cursor query with some refactoring introducing a SQL syntax error. All I saw in the console was an uncaught error emitted by the pg connection saying syntax error near "$1". Is there any way node-pg-cursor can catch such errors? I had to add a log statement to the pg source to log all queries before I realized it was a cursor query I had broken, so it's not a very good user experience.

@brianc I'm confused why there's a Cursor.prototype.handleError method but it doesn't seem to be referenced anywhere. Did someone forget to add connection.on('error', this.handleError)?

@brianc okay turns out my issue is probably due to the fact that I'm using pg 7 and this package is tested on pg 6. Peer deps are important.