'How to return HTTP error status code in Node?

What is the most efficient way to return an error number or error status code in JavaScript / NodeJS? For example, I would like to return a status code (or error code) of 401 in the following snippet:

var login = function (params, callback) {

    var email       = params.email || '',
        password    = params.password || '';

    if (!isValidEmail(email)) { 
        return callback(new Error('Email address required', 401)); 
    }

    // Do something else
};

The login method, above, would be called as follows:

authRouter.post('/login', function(req, res) {
   svc.login(req.body, function (err, response) {
       if (err) {
           err.statusCode = err.statusCode || 401;
           return res.status(err.statusCode).send({ message: err.message });
       } else {
           return res.send(response);
       }
   });
});

The goal here is to have the err.statusCode (or similar) set in the method and passed back via the callback. Basically, I'm looking for a shorthand version of this:

var err = new Error('Email address required');
err.statusCode = 401;
return callback(err);


Solution 1:[1]

In nodeJS you should ever return your error in the first argument of your callbacks.

myFunctionThatDoesSomethingAsync (callback) {
  doSomethingAsync('asanas', function (){
    //do something 
    return callback(err,results)
  })
}

myFunctionThatDoesSomethingAsync(function (err,results) {
  if (!err)
    doSomethingWith(results)
})

read more: http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/

Sorry I read your question again and ysing NodeJS HTTP response you should do something like:

res.writeHead(401, {'Content-Type': 'text/plain'});
res.end('Email address required'');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 royhowie