Reputation: 1897
How can I make my node js application fail safe. I wrote the db query wrapper, some provider(to work with user for example, and my controllers(routes))
Function for db connection:
exports.connect = function(callback) {
sqlClient.connect(function(err, conInfo){
if (err) callback(err);
conInfo = 'Connection at ' + sqlClient.host + ':' + sqlClient.port + '/'
+ sqlClient.database + ' used by ' + sqlClient.user;
callback(null, conInfo);
//runDDL();
});
};
Function for query:
exports.runQuery = function(query_str, columns, params, callback) {
var sqlQuery = query_str + " " + columns;
var query = sqlClient.query(sqlQuery, params, function(err) {
if (err) throw err;
console.log('NEW QUERY____________________');
console.log(sqlQuery);
console.log(params);
if (err) throw err;
query.on('row', function(row, result) {
result.addRow(row);
});
query.on('end', function (result) {
callback(null, result.rows);
});
});
};
Provider function:
User.prototype.get = function(id, callback) {
db.runQuery('SELECT * FROM users', 'WHERE id=$1', [id],
function(err, allUsers){
if (err) throw err;
callback(null, allUsers[0]);
});
};
Usage in controller:
exports.getById = function(req, res) {
var id = req.params.user_id;
userProvider.get(id, function(err, user){
if (err) throw err;
res.send(user);
});
};
In any unexpected situation my server will print error and process will die. How to easier handle some type of errors, for example let's consider that req.params.user_id
will be more then number of records in the database.
As you see I just throwing errors with throw err
. Is there more fail safe and efficient practice to handle errors, and print to client understandable information, keeping server working?
Upvotes: 0
Views: 498
Reputation: 2418
You can write your own error handler with express: Refer example below:
https://github.com/visionmedia/express/blob/master/examples/error/index.js
Upvotes: 2