Advertisement
dereksir

Untitled

Dec 12th, 2023 (edited)
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const axios = require('axios');
  2. const retry = require('retry');
  3.  
  4. function faultTolerantHttpRequest(URL, cb) {
  5.     // Initialize a retry operation with custom settings
  6.     const operation = retry.operation({
  7.     retries: 5,            // Maximum number of retry attempts
  8.     factor: 2,             // Exponential backoff factor
  9.     minTimeout: 1000,      // Minimum timeout (in milliseconds)
  10.     maxTimeout: 60 * 1000, // Maximum timeout (in milliseconds)
  11.     randomize: true,       // Randomize the timeouts
  12. });
  13.  
  14.     operation.attempt(function(currentAttempt) {
  15.         // Make an HTTP GET request to http://httpbin.io/status/500
  16.         axios.get(URL)
  17.             .then((response) => {
  18.                 // If the request is successful, resolve the Promise with the response body
  19.                 cb(null, response.data);
  20.             })
  21.             .catch((error) => {
  22.                 // If there's an error, check if retry is allowed.
  23.                 if (operation.retry(error)) {
  24.                     return;
  25.                 }
  26.  
  27.                 // If all retry attempts are exhausted, reject with the main error
  28.                 cb(operation.mainError());
  29.             });
  30.     });
  31. };
  32.  
  33. faultTolerantHttpRequest('https://httpbin.io/status/500', function(error, result) {
  34.   if (error) {
  35.     // Handle the error
  36.     console.error('Error:', error);
  37.   } else {
  38.     // Process the successful result
  39.     console.log('Result:', result);
  40.   }
  41. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement