S
S
stas_mihailov2020-04-17 19:02:00
JavaScript
stas_mihailov, 2020-04-17 19:02:00

How to handle a request error from the server?

There is a function that dispatches events and makes a request. I handle errors internally with try/catch...
How can I access it externally to catch the error ?
Now I'm doing this, but everything flies to then (you need to catch):

checkEmail({ email }).then((resolve) => {
            console.log("resolve:" + resolve);
        })
        .catch((reject) => {
            console.log("reject:" + reject);
        });


The function itself:
export const checkEmail = ({ email }) => async (dispatch) => {
  dispatch({
    type: FORM_LOADING,
  });

  try {
    const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };

    const res = await axios.get(`/api/users?email=${email}`, email, config);
    dispatch({
      type: CHECK_EMAIL,
      payload: res.data,
    });

  } catch (err) {
    const errors = err.response.data.errors;
    if (errors) {
      dispatch({
        type: FORM_ERROR,
      });
      return errors[0].msg;
    }
  }
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-04-17
@stas_mihailov

move the error further up

catch (err) {
    const errors = err.response.data.errors;
    if (errors) {
      dispatch({
        type: FORM_ERROR,
      });
      // return errors[0].msg;
      throw new Error(errors[0].msg)
    }
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question