乐闻世界logo
搜索文章和话题

How to retry 5xx requests using axios

1个答案

1

When making HTTP requests with Axios, if you encounter a 5xx error (i.e., server error), you can implement automatic retries in several different ways.

1. Using the axios-retry Library

axios-retry is a widely adopted library that simplifies implementing automatic retries with Axios. First, install this library:

bash
npm install axios-retry

Then, import and configure the retry strategy in your code, for example:

javascript
const axios = require('axios'); const axiosRetry = require('axios-retry'); // Create an Axios instance const axiosInstance = axios.create({ // Configuration... }); // Install the axios-retry plugin and configure automatic retries axiosRetry(axiosInstance, { retries: 3, // Set the number of retries retryCondition: (error) => { // Retry only for 5xx server errors return error.response && error.response.status >= 500; }, retryDelay: (retryCount) => { // Calculate the retry interval using exponential backoff return axiosRetry.exponentialDelay(retryCount); } }); // Use axiosInstance to make requests axiosInstance.get('https://example.com/api') .then(response => { // Handle response }) .catch(error => { // Handle error });

2. Using Axios Interceptors

You can implement retry logic using Axios's interceptors feature, which allows you to intercept requests or responses before processing and execute custom code.

javascript
const axios = require('axios'); // Define maximum retry count const MAX_RETRIES = 5; let retries = 0; axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) { if (err.response && err.response.status >= 500 && retries < MAX_RETRIES) { retries += 1; // Increment retry count return axios(err.config); // Reissue the request } return Promise.reject(err); // Reject if retry conditions are not met }); // Use axios to make requests axios.get('https://example.com/api') .then(response => { // Handle response }) .catch(error => { // Handle error });

3. Manual Retry

You can also manually implement retry logic. For instance, create a function that encapsulates the Axios request and recursively retries on 5xx errors.

javascript
const axios = require('axios'); function requestWithRetry(url, retries = 5) { return axios.get(url) .then(response => response) .catch(error => { if (error.response && error.response.status >= 500 && retries > 0) { // Wait briefly before retrying return new Promise(resolve => { setTimeout(() => resolve(requestWithRetry(url, retries - 1)), 1000); }); } // Throw error if retries are exhausted or other issues occur throw error; }); } // Use the function to make requests requestWithRetry('https://example.com/api') .then(response => { // Handle response }) .catch(error => { // Handle error });

In the above example, the requestWithRetry function attempts a GET request. If the response is a 5xx error and retries remain, it waits 1 second before retrying. Adjust the retry interval and count based on your specific scenario.

Note that frequent retries for server requests may cause excessive server load, so when implementing retry strategies, exercise caution and consider appropriate backoff strategies (such as exponential backoff used in the examples). Additionally, ensure to differentiate between network instability and scenarios where the server genuinely requires time to recover.

2024年6月29日 12:07 回复

你的答案