dimanche 12 juillet 2015

NodeJS SQLite Error Exception

I am currently trying to create a server using NodeJS to provide RESTful APIs for inserting records into a SQLite database. While I am able to retrieve records, I am having issues handling SQLite related errors (e.g. unique constraints):

function insertUser(name, password) {
    db.run(insert_stmt, [name, password, new function(err) {
       if (err != null) {
           handleError(err, response);
       }
        else if (response != null) {
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.write("User registered.");
            response.end();
        }
    }, function(err) {
        handleError(err, response);
    });
}

function handleError(err, response) {
    console.log(err.message);
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Registration error.");
    response.end();
}

The problem is that the code appears to be hitting both the second and the third function, as the response object appears to be closed whenever I try to create a response in the handleError method. In my browser, I am getting the "User registered." message as a response.

SQLITE_CONSTRAINT: UNIQUE constraint failed: Users.name, Users.phone_no
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: write after end
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15)
    at handleError (/Users/kli/Documents/Node.js/db.js:59:14)
    at Statement.<anonymous> (/Users/kli/Documents/Node.js/db.js:39:3)
    at Statement.replacement (/Users/kli/node_modules/sqlite3/lib/trace.js:20:31)
    at Statement.replacement (/Users/kli/node_modules/sqlite3/lib/trace.js:20:31)

What is the correct way of handling errors in NodeJS? I tried using the process.on('uncaughtException', function(err) method, but I need the response object in order send a response to the client, indicating the error that has occurred.

Aucun commentaire:

Enregistrer un commentaire