hapi.js best way to handle errors
hapi.js, javascript, node.js, rest
Solution
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);
}
}();
Problem
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 } } }(); ```