DEV Community

Discussion on: Axios Async/Await with Retry

Collapse
 
yogski profile image
Yogi Saputro

Hi,
It's okay to not use timeout.
In this case, if you receive 400 or 500 status, it will automatically retry the request.
However, please note that those response are considered error, so it will be catched.

To handle 400 or 500 status, put your logic after catch(error)

const rax = require('retry-axios');
const axios = require('axios');

rax.attach();
const myRequest = async () => {
  try {
    const myConfig = {
      raxConfig: {
        retry: 5, // number of retry when facing 400 or 500
        onRetryAttempt: err => {
          const cfg = rax.getConfig(err);
          console.log(`Retry attempt #${cfg.currentRetryAttempt}`); // track current trial
        }
      },
    }
    const req = await axios.get('https://mock.codes/500', myConfig);
    console.log(req.data);
  } catch (error) {
    // 400 or 500 response will be handled here
    console.log(error.response.status);
    // continue your code here ...
  }
}

myRequest();
Enter fullscreen mode Exit fullscreen mode

Hope this helps.