Edward Tanguay
Edward Tanguay

Reputation: 193442

How to communicate an error that occurred in Node to the web user?

I'm looking for a simplistic error handling solution in my node application so that it doesn't fail on every error.

I'm well aware that the following approach is "a very crude mechanism" (from the Node documentation), but I'm also aware that domains are depreciated, and solutions involving clusters and a supervisor that I have looked at are quite complicated and introduce other problems. I merely need a way for my node server to not completely fail and be unavailable for all users each time any error that occurs.

This process.on solution seems to work well enough.

However, given this solution, how can I inform the web user that there was an error?

For instance, this is a method that executes SQL on an SQLite database, and if there is an error, I want to pass a message to the code that called this method, so that that code can pass it onto the web user:

exports.executeSql = function(sql) {

    process.on('uncaughtException', function (err) {
        console.log("ERROR: " + err); // WORKS, BUT ONLY SERVER-SIDE
        return "There was an error but it was handled."; //IGNORED
      });

    var sqlite3 = require('sqlite3').verbose();
    var db = new sqlite3.Database('data/main.sqlite');
    var status = "error";

    db.serialize(function() {        
        db.run(sql);
        status = "ok"; //ALWAYS EXECUTED WHETHER THERE WAS AN ERROR OR NOT
    });

    db.close();

    return status;
}

Upvotes: 0

Views: 27

Answers (1)

11AND2
11AND2

Reputation: 1157

I don't think that you really want to notify your users in detail about system errors for security reasons.

However, I assume that you have a way to respond to a users request (eg websockets). So you could do something like this (dummy code):

server.on('user_wants_something', function(err,req) {
   var _res = executeSql('abc');
   //error, send to user
   if (_res.state === 1) {
     server.send('return_user_wants_something_error', _res);
     return;
   }
   ...do normal request handling...
});

var executeSql = function(sql) {

  process.on('uncaughtException', function (err) {
    console.log("ERROR: " + err); // WORKS, BUT ONLY SERVER-SIDE
    return {
       state: 1, //error state
       message: "There was an error but it was handled."; //error message
    }
  });
  ...
  //good result
  return {
    state: 0, //clean state
    message: [...my query data...] //result data
  }
}

Upvotes: 1

Related Questions