在客户端和服务器端处理错误消息

时间:2019-08-11 17:15:11

标签: node.js reactjs mongodb

我已经创建了一个用户注册页面,我希望能够处理各种错误器,我确定我的代码可以正常工作,但是令我惊讶的是,当输入不正确时,我没有看到错误消息。

我尝试使用Chrome,该错误消息似乎仅出现在控制台中,但对用户不可见。

export default class UserController {
  static async register(req, res) {
    try {
      const userFromBody = req.body
      let errors = {}
      if (userFromBody && userFromBody.password.length < 8) {
        errors.password = "Your password must be at least 8 characters."
      }
      if (userFromBody && userFromBody.name.length < 3) {
        errors.name = "You must specify a name of at least 3 characters."
      }

      if (Object.keys(errors).length > 0) {
        res.status(400).json(errors)
        return
      }

      const userInfo = {
        ...userFromBody,
        password: await hashPassword(userFromBody.password),
      }

      const insertResult = await UsersDAO.addUser(userInfo)
      if (!insertResult.success) {
        errors.email = insertResult.error
      }
      const userFromDB = await UsersDAO.getUser(userFromBody.email)
      if (!userFromDB) {
        errors.general = "Internal error, please try again later"
      }

      if (Object.keys(errors).length > 0) {
        res.status(400).json(errors)
        return
      }

      const user = new User(userFromDB)

      res.json({
        auth_token: user.encoded(),
        info: user.toJson(),
      })
    } catch (e) {
      res.status(500).json({ error: e })
    }
  }

我希望用户能够看到导致错误的原因,例如,如果用户密码少于7个字符,那么我想显示适当的错误消息。

0 个答案:

没有答案