NodeJS和ExpressJS有没有比我正在做的更好的方法来处理错误响应?

时间:2015-03-07 16:36:32

标签: node.js express

下面我有一个非常基本的帖子请求来通过REST API创建用户。目前,如果我有一个错误状态发生的地方,我正在更新响应对象并返回该函数。我的问题是有更好的方法吗?还是我走在正确的轨道上?

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

1 个答案:

答案 0 :(得分:3)

您可以创建错误中间件,只需将Error实例传递给next回调:

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

在所有路线之后注册中间件:

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