Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  165] [ 1]  / answers: 1 / hits: 22655  / 10 Years ago, thu, july 10, 2014, 12:00:00

I'm creating my first node.js REST web service using hapi.js. I'm curious as to the best way to handle errors let's say from my dao layer. Do i throw them in my dao layer and then just try/catch blocks to handle them and send back errors in my controller, or is there a better way that the cool kids are handling this?



routes/task.js



var taskController = require('../controllers/task');
//var taskValidate = require('../validate/task');

module.exports = function() {
return [
{
method: 'POST',
path: '/tasks/{id}',
config : {
handler: taskController.createTask//,
//validate : taskValidate.blah
}
}
]
}();


controllers/task.js



var taskDao = require('../dao/task');

module.exports = function() {

return {

/**
* Creates a task
*
* @param req
* @param reply
*/
createTask: function createTask(req, reply) {

taskDao.createTask(req.payload, function (err, data) {

// TODO: Properly handle errors in hapi
if (err) {
console.log(err);
}

reply(data);
});

}
}();


dao/task.js



module.exports = function() {

return {
createTask: function createTask(payload, callback) {

... Something here which creates the err variable...

if (err) {
console.log(err); // How to properly handle this bad boy
}
}
}();

More From » node.js

 Answers
12

In doing more research along with Ricardo Barros' comment on using Boom, here's what I ended up with.



controllers/task.js



var taskDao = require('../dao/task');

module.exports = function() {

return {

/**
* Creates a task
*
* @param req
* @param reply
*/
createTask: function createTask(req, reply) {

taskDao.createTask(req.payload, function (err, data) {

if (err) {
return reply(Boom.badImplementation(err));
}

return reply(data);
});

}
}();


dao/task.js



module.exports = function() {

return {
createTask: function createTask(payload, callback) {

//.. Something here which creates the variables err and myData ...

if (err) {
return callback(err);
}

//... If successful ...
callback(null, myData);
}
}();

[#70245] Tuesday, July 8, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
peytont

Total Points: 215
Total Questions: 110
Total Answers: 111

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;