trycatch block not sent error when error triggers

Viewed 28

iam using react-redux here and when i use trycatch block it not triggers error when error is executed.why??

    import {
      LOGIN_REQUEST,
      LOGIN_SUCCESS,
      LOGIN_FAIL,
      CLEAR_ERRORS,
    } from "../constants/userConstant";
    impo

rt axios from "axios";
export const login = (email, password) => async (dispatch) => {
  try {
    dispatch({ type: LOGIN_REQUEST });
    const config = { headers: { "Content-Type": "application/json" } };
    const { data } = await axios.post(
      `/api/v1/login`,
      { email, password },
      config
    );
    dispatch({ type: LOGIN_SUCCESS, payload: data.user });
  } catch (error) {
    dispatch({ type: LOGIN_FAIL, payload: error.response.data.message });
  }
};
//Clearing errors
export const clearErrors = () => async (dispatch) => {
  dispatch({ type: CLEAR_ERRORS });
};

=>It was showing LOGIN_FAIL in react-redux-devtools but it was not throwing an error

1 Answers
catch (error) {
  dispatch({ type: LOGIN_FAIL, payload: error.response.data.message });  
  
  // Log your error in the console
  console.log(error);
  
  // throw error
  throw error
}

If you want to console error or throw error do it this way but you actually just call your dispatch for the moment.

The try catch blocks are here to handle every situations your function meet, when an error come it's been caught but YOU have to decide how to handle this error.

Related