Quentin
Quentin

Reputation: 371

How to prevent axios.interceptors.response.use to crash the error handling?

I have several forms "Login, Registration, Create a product..." For these forms, I was handling errors with useState for the front end and for the back end with express-validator.

Everything worked perfectly, I received error messages as expected.

But now, I realize that none of these forms manage errors anymore. Since I set up my axios.interceptors.response.use to send the user back to the login page if he has a 403 status (This is my way of handling a token that expires).

Here is my code that NORMALLY shows me the errors : (For example, this is my login page where I only get one error message)

axios.interceptors.request.use(
  (config) => {
    config.headers.authorization = `Bearer ${localStorage.getItem('UserToken')}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response.status === 403) {
      localStorage.clear();
      window.location.href = '/connexion';
    }
  },
);

export default function ConnexionPage() {
  // Redirection Connexion réussite vers Accueil
  const history = useHistory();

  const [errorForm, setErrorForm] = useState();

  // Connexion
  const handleSubmit = (event) => {
    event.preventDefault();
    login(event.target.email.value, event.target.password.value)
      .then((response) => {
        const Token = response.data.accessToken;
        localStorage.setItem('UserToken', Token);
        User = jwt_decode(Token);
        localStorage.setItem('User', JSON.stringify(User));
        history.push({
          pathname: '/',
        });
        window.location.reload(false);
      })
      .catch((err) => {
        setErrorForm(err.response.data);
      });
  };

  // Classe de style
  const classeConnexion = ConnexionStyle();

  return (
    <Grid>
      <Card style={{ height: 500, marginTop: '5%', marginRight: '10%', marginLeft: '10%' }} variant="outlined">
        <Grid align="center">
          <Avatar className={classeConnexion.avatar}>
            <LockOutlinedIcon></LockOutlinedIcon>
          </Avatar>
          <h2>Connexion :</h2>
          {errorForm && <p style={{ color: 'red' }}>{errorForm}</p>}
        </Grid>

        <form onSubmit={handleSubmit}>
          <TextField
            id="email"
            name="email"
            label="Email :"
            placeholder="Entrez votre mail."
            fullWidth
            variant="outlined"
            style={TextFieldStyle}
            required
          />

          <TextField
            style={TextFieldStyle}
            id="password"
            name="password"
            label="Mot de passe :"
            placeholder="Entrez votre mot de passe."
            type="password"
            fullWidth
            variant="outlined"
            required
            autoComplete="on"
          />

          <Button endIcon={<CheckIcon />} className={classeConnexion.root} type="submit" variant="contained" fullWidth>
            Connexion
          </Button>
        </form>

        <Typography>
          <Link href="/inscription">Pas de compte ? Créez-en un.</Link>
        </Typography>
      </Card>
    </Grid>
  );
}

PS: I'm still a simple student, having to make an e-commerce site as an exercise.

EDIT : Yes, it's my axios.interceptors.response.use that make my error handling getting ignored or make the application crash

Upvotes: 6

Views: 6730

Answers (1)

Haseeb Anwar
Haseeb Anwar

Reputation: 2918

You've missed one thing, to return the error from axios response interceptor when error.response.status is not 403

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response.status === 403) {
      localStorage.clear();
      window.location.href = "/connexion";
    }

    // reject with error if response status is not 403
    return Promise.reject(error);
  }
);

);

Upvotes: 10

Related Questions