11

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);
3
  • You mean, send to the client? What framework are you using? Commented Nov 6, 2015 at 2:15
  • Using Node ... shouldn't matter what I do with it, I just want the error object to contain the numeric value. Commented Nov 6, 2015 at 2:24
  • 1
    If that's the problem, just use a helper function StatusError(stat, msg) { var err = new Error(msg); err.statusCode = stat; return err; } then Commented Nov 6, 2015 at 2:26

2 Answers 2

8

You can create your own error class for something like this. I've done something similar on several projects:

class HttpError extends Error {
    constructor (message, statusCode) {
        super(message);
        this.statusCode = statusCode;
    }
}

Now you can use it the way you expected it to work:

return callback(new HttpError('Email address required', 401)); 

Personally I prefer to create individual error types for the kinds of error my app use to make the code more readable. When you're in a rush, especially if you have junior developers working on your code, you will find that most people won't remember what 401 error is. I normally do something like this:

class UnauthorizedError extends Error {
    constructor (message) {
        super(message);
        this.statusCode = 401;
    }
}

class ForbiddenError extends Error {
    constructor (message) {
        super(message);
        this.statusCode = 403;
    }
}

class NotFoundError extends Error {
    constructor (message) {
        super(message);
        this.statusCode = 404;
    }
}

So I'd use them like this:

return callback(new UnauthorizedError('Email address required'));

IMHO this makes the code more readable and also makes the error codes self-documenting in the source code.

Sign up to request clarification or add additional context in comments.

Comments

-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'');

1 Comment

That's not the question. My goal is to include a numeric value (a status code) on the error object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.