2
\$\begingroup\$

I have this ExpressJS route for saving and listing Category model.

exports.save = function(req, res, next){
  //validate here>>>
  var name = req.body.name;
  var description = req.body.description;

  new Category({
    name: name,
    description: description,
  }).save(function(err, docs){
    if ( err ) {
      console.log('error: saving category');
      next(error);
    }else{
      console.log('category saved.');
      res.redirect('categories');
    }
  });
}


exports.list = function(req, res, next){
  Category.find(function ( err, categories, count ){
    if (err) {
      console.log('error: listing categories');
      next(error);
    }
    res.render( 'categories/list', {
        categories : categories
    });
  }); 
}

Is having console.log and next(error) OK? How could I improve the above code in terms of conventions in NodeJS / ExpressJS?

\$\endgroup\$
1
  • \$\begingroup\$ Instead of the console.log you could use console.error to print errors. It's the same as console.log but it prints to stderr. I bet you've seen this in the documentation of express.js. \$\endgroup\$ Feb 5 '14 at 17:23
2
\$\begingroup\$

I assume you have a typo there, error is nowhere defined but you do have err.

To jackdbernier's point, you should read the docs: http://expressjs.com/guide.html#users-online

In there it is clear that you should call next regardless whether you have an error or not, otherwise not all middlewares will be processed.

If you insist on logging before call next, you could.

function handleError( message , err , next )
{
  console.error( message );
  return next( err );
}

new Category({
  name: name,
  description: description,
}).save(function(err, docs){
  if ( err ){
    return handleError( 'error: saving category' , err, next );
  } 
  console.log('category saved.');
  res.redirect('categories');
  next(); // <- this!
});
}

Though I would personally drop the curly braces from that if( err ).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.