Error response is undefined when I get 504 error in axios

Viewed 1563

If i got any 404 error then logging the error in catch block has that status code but if i get an 504 error from server then logging error.response in catch is undefined. Any reason why that happens?

try {
  const response = await axios.request({
    method,
    url,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
    },
    ...config,
  });
  return response;
} catch (error) {
  console.dir(error);
  if (error.response && error.response.status === 401) {
    const isNonAuthUrl = window.location.pathname.match(/\/verify\//);
    if (!isNonAuthUrl) {
      localStorage.clear();
      window.location.reload();
    } else {
      throw error;
    }
  } else {
    throw error;
  }
}
1 Answers
try {
  const response = await axios.request({
    method,
    url,
    timeout: 1000, //1000ms
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
    },
    ...config,
  });
  return response;
} catch (error) {
  console.dir(error);
  if (error.response && error.response.status === 401) {
    const isNonAuthUrl = window.location.pathname.match(/\/verify\//);
    if (!isNonAuthUrl) {
      localStorage.clear();
      window.location.reload();
    } else {
      throw error;
    }
  } else {
    throw error;
  }
}

The default axios behaviour for timeout is 0 that means no timeout. So it will never be catched incase the request is taking more time. Try adding timeout specifically to the request then axios will abort the request with an error which can be catched in the catch block. In the above example I have added 1 sec timeout.

Related