Andrew Atwood
Andrew Atwood

Reputation: 77

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

I am creating a react native project mostly just to learn and I am having an issue with catching some of my error messages in the react-native side from my express server. My express server is using express-validator to do some preliminary validation. The express-validation part works as I am able to use postman to retrieve the response (i.e. 'Please enter a password with 8 characters'), but I can never get these errors to send successfully to RN. Even trying to send JSON in response to an 'error' I intentionally create seems to not allow me to catch it.

Below is the signup route, the utility function (imported from another file), and the chunk of code that I believe should be catching the error. I am not very good at asking for help, so if any additional information would benefit those willing to assist, please let me know.

//SIGNUP ROUTE

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

} );

// UTILITY FUNCTION

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

},

//CODE IN React-Native TO CATCH ERROR

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

};

Upvotes: 0

Views: 631

Answers (1)

Andrew Atwood
Andrew Atwood

Reputation: 77

Welp, as embarrassing as this is to admit, I managed to solve my own problem. I had tried many variations of logging the response, but I did not delve deep enough. I had tried the following.

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

Turns out I just need to actually think for 2 minutes and figure out the nesting.

The errors were being passed in error.response.data.errors.

I do appreciate Muhammads help though.

Upvotes: 2

Related Questions