无法从我的 express 后端捕获我的 React Native 项目中的错误

Unable to catch my errors in my react native project from my express backend

我正在创建一个 React Native 项目,主要是为了学习,我在从我的快速服务器的 React-Native 端捕获我的一些错误消息时遇到了问题。我的 express 服务器正在使用 express-validator 进行一些初步验证。快速验证部分有效,因为我能够使用邮递员检索响应(即 'Please enter a password with 8 characters'),但我永远无法将这些错误成功发送给 RN。即使尝试发送 JSON 以响应我故意创建的 'error' 似乎也不允许我捕捉到它。

下面是注册路径、实用函数(从另一个文件导入)和我认为应该捕获错误的代码块。我不太擅长寻求帮助,所以如果任何其他信息对愿意提供帮助的人有帮助,请告诉我。

//注册路线

router.post(


// accrue validation checks
  '/signup',
  [body('userName', 'Please choose a username name.').not().isEmpty()],
  [
    body(
      'password',
      'Please enter a password with at least eight characters'
    ).isLength({ min: 8 }),
  ],
  (req, res) => {
    // send accrued validation checks
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(401).json({ errors: errors.array() });
    }

// hash password and store new user in database, then send back a JWT
bcrypt.genSalt(10, (err, salt) => {
  bcrypt.hash(req.body.password, salt, (err, hash) => {
    connection.query(
      `INSERT INTO user (user_name, email, hashed_password, first_name, last_name)
      VALUES ('${req.body.userName}', '${req.body.email}', '${hash}', '${req.body.firstName}', '${req.body.lastName}')`,
      (error, results, fields) => {
        if (error) {
          res.status(401).json({ error: error.message });
        } else {
          let userName = req.body.userName;
          console.log(userName);
          UtilityFunctions.returnJWT(res, req.body.userName);
        }
      }
    );
  });
});

} );

//效用函数

  returnJWT: (res, userName) => {
const payload = {
  user: {
    userName,
  },
};
jwt.sign(payload, secret, {}, (err, token) => {
  if (err) throw err;
  res.send(token);
});

},

//React-Native 中的代码捕获错误

const authenticate = async (e) => {
e.preventDefault();
  try {
    let res = await axios.post(url, {
      headers: {
        'Content-Type': 'application/json',
      },
      userName: userName,
      password: password,
      password2: password2,
    });
    // Clears local state after successful authentication
    let token = res.data;
    dispatch(storeAuthToken(token));
    props.navigation.navigate(Dashboard);
  } catch (err) {
    console.log(err, err.message, err.errors);
    if ((err.message = 'Request failed with status code 401')) {
      setError('Invalid credentials. Please try again.');
    } else {
      setError('Woops! Something went wrong. Please try again.');
    }
    setTimeout(() => {
      setError('');
    }, 4000);
  }

};

好吧,尽管承认这很尴尬,但我设法解决了自己的问题。我尝试了多种记录响应的变体,但我没有深入研究。我试过以下方法。

console.log(error)
console.log(error.errors)
console.log(error.response.errors)
console.log(reponse)

结果我只需要实际思考 2 分钟并弄清楚嵌套。

在 error.response.data.errors 中传递了错误。

虽然我很感谢穆罕默德的帮助。