'How to display the back-end error message instead of status code

I created a Backend server and posted it to Heroku and now I am using the server URL to post and get data from it. However when I display an error message it's getting me the status code instead of the actual error.

My Backend login code.

 export const loginUser = asyncHandler(async(req, res) => {
  const { email, password } = req.body;

  const user = await userModel.findOne({ email });

  const token = generateToken(user._id)

  if(user && (await user.matchPassword(password))){
    res.json({
      _id:user._id,
      username: user.username,
      email: user.email,
      profilePic:user.profilePic,
      admin:user.admin,
      token:token,

    });

  } else {
    res.status(400)
    throw new Error("invalid email or password please check and try again!");
  }

});

My user Actions code since I am suing redux

    export const login = (email, password) => async (dispatch) => {
    try {
    dispatch({
      type: USER_LOGIN_REQUEST,
    });

    const url = `${process.env.REACT_APP_SERVER_URL}api/loginuser`;
    const config = {
      headers: {
        "Content-type": "application/json",
      },
    };
    const { data } = await axios.post(
      url,
      {
        email,
        password,
      },
      config
    );

    dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    });
    localStorage.setItem("userInfo", JSON.stringify(data));
   } catch (error) {
    dispatch({
      type: USER_LOGIN_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

Error in frontend display How the error is displayed



Solution 1:[1]

you need to return response instead of throwing the error:

res.status(400)
res.json({
 message: "invalid email or password please check and try again!"
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sina.ce