thenetimp
thenetimp

Reputation: 9830

NodeJS and ExpressJS is there a better way to handle error responses than what I am doing?

Below I have a very basic post request to create a user via REST API. Currently if I have a place where an error state happens I am updating the response object and returning the function. My question is there a better way to do this? Or am I on the right track?

  app.post('/api/user/create', function (request, response)
  {
    // Create variables foreach input.
    var firstName, lastName, emailAddress, password, passwordConfirm, User;
    firstName = validator.trim(request.body.firstName);
    lastName = validator.trim(request.body.lastName);
    emailAddress = validator.trim(request.body.emailAddress);
    password = validator.trim(request.body.password);
    passwordConfirm = validator.trim(request.body.passwordConfirm);

    if(!validator.isEmail(emailAddress))
    {
      response.status(500).send({error: true, message: "ERROR_INVALID_EMAIL"});
      return;
    }

    if(password != passwordConfirm)
    {
      response.status(500).send({error: true, message: "ERROR_INPUT_COMPARATOR_PASSWORD_INVALID"});
      return;
    }

    User = db.User;
    User.create({
      firstName: firstName,
      lastName: lastName,
      emailAddress: emailAddress,
      password: passwd.crypt(password)
    }).then(function()
    {
      response.status(200).send({error: false, message: "SUCCESS_USER_CREATED"});
    }).error(function(error)
    {
      console.log(error);
      response.status(500).send({error: true, message: error.errors});
    });
  });

Upvotes: 0

Views: 49

Answers (1)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12334

You can create an error middleware and just pass the Error instance to next callback:

if(!validator.isEmail(emailAddress))
{
  var error = new Error();
  error.message = "ERROR_INVALID_EMAIL";
  return next(error);
}

Register the middleware after all the routes:

app.use(function (err, req, res, next) {
    return res.status(500).send({error: true, message: err.message});
});

Upvotes: 3

Related Questions