• Stars
    star
    188
  • Rank 205,563 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Transient exception handling for JavaScript

polly-js

Greenkeeper badge Transient exception handling for JavaScript made easy.

npm version Bower npm downloads Dependency Status Build Status codecov.io

Polly-js is a library to help developers recover from transient errors using policies like retry or wait and retry.

Polly-js

The typical use case for polly-js are retrying actions after they fail. These actions often include some form of IO which can fail. Examples of these IO actions are AJAX requests to other services, file operations on disk or interacting with a database. All these actions share the characteristics that they can occasionally fail because of circumstances outside of the control of your application like the network connection might be briefly unavailable or the file might be in use by another process. When any of these actions fail there is a change that just retrying the same action, possibly after a short delay, will work. Polly-js makes these retry actions easy to code.

Detecting failures

Depending on the function being executed different ways of detecting failure are used.

When you call polly().execute(<your function>) the code assumes that your code failed and needs to be retried when your function throws an Error.

When you call polly().executeForPromise(<your function>) the code assumes that your code failed and needs to be retried when your function returns a Promise that is rejected.

When you call polly().executeForNode(<your function that accepts a callback>) the code assumes that your code failed and needs to be retried when your function calls the callback with a first non null parameter indicating an error.

Deciding what to do on failure

Whenever a failure is detected Polly-js will attempt to retry your action.

You get to control how a failure is retried by calling either polly().retry() or polly().waitAndRetry(). Both will retry the failing action but the polly().waitAndRetry() option adds a small delay before retrying. In general polly().waitAndRetry() is probably the more appropriate policy to use as retrying without apause could cause a lot requests. By default both will retry once where polly().waitAndRetry() waits 100 ms before retrying. With either function you can specify a number of retries to attempt on repeated failures. With polly().waitAndRetry() it will double the time between each try. If you want to control the exact delays you can also specify and array with the individual delay values so polly().waitAndRetry(5) is equivalent to polly().waitAndRetry([100, 200, 400, 800, 1600]).

Deciding what failures to retry

Using polly().handle(<function>) you can decide if you want to retry a specific failure. For example you might want to retry an AJAX request returning a 404 response code but not one resulting in a 500 response code. The callback function specified in polly().handle() is called with watever error was received so you can use any property from there and you return true if you want to retry the action or false to stop retrying.

Usage

Try to load the Google home page and retry twice if it fails.

polly()
    .retry(2)
    .executeForPromise(function () {
        return requestPromise('http://www.google.com');
    })
    .then(function(result) {
        console.log(result)
    }, function(err) {
        console.error('Failed trying three times', err)
    });

Try to read a file from disk and retry twice if this fails.

polly()
    .retry(2)
    .executeForNode(function (cb) {
        fs.readFile(path.join(__dirname, './hello.txt'), cb);
    }, function (err, data) {
        if (err) {
            console.error('Failed trying three times', err)
        } else {
            console.log(data)
        }
    });

Only retry 'no such file or directory' errors. Wait 100 ms before retrying.

polly()
    .handle(function(err) {
        return err.code === 'ENOENT';
    })
    .waitAndRetry()
    .executeForNode(function (cb) {
        fs.readFile(path.join(__dirname, './not-there.txt'), cb);
    }, function (err, data) {
        if (err) {
            console.error('Failed trying twice with a 100ms delay', err)
        } else {
            console.log(data)
        }
    });

Use async await with the browsers fetch API.

const loadData = url => {
  return polly()
    .waitAndRetry(2)
    .executeForPromise(async () => {
      const rsp = await fetch(url);
      if (rsp.ok) {
        return rsp.json();
      }
      return Promise.reject(rsp);
    });
};

// Using the function somewhere else:
const movies = await loadData("http://localhost:3000/movies.json");

Logging errors

You can set a logger function to be called every time an error is detected.

polly()
    .logger(function(err){
        console.error(err); //will be hit 2 times
    })
    .retry(2)
    .executeForPromise(function () {
        return requestPromise('http://foo.bar.com');
    })
    .then(function(result) {
        //do some important stuff here
    }, function(err) {
        console.error('Failed trying three times', err);//third error is passed back to the caller
    });

Acknowledgements

The library is based on the Polly NuGet package by Michael Wolfenden

See Also

  • Cockatiel: A more feature rich package that includes polies like Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback.

More Repositories

1

use-abortable-fetch

React hook that does a fetch and aborts when the components is unloaded or a different request is made
TypeScript
158
star
2

server-side-rendering-with-create-react-app

Server-side Rendering with Create-React-App
JavaScript
32
star
3

gulp-main-bower-files

Use main-bower-files in a more gulp like way.
JavaScript
27
star
4

react-chrome-extension

HTML
20
star
5

advanced-react-typescript-2022

TypeScript
17
star
6

RawStack

Building applications using the RAW stack. RavenDB, AngularJS and ASP.NET WebAPI
JavaScript
17
star
7

presentation-buddy

Automatically type code during presentations
TypeScript
16
star
8

master-rxjs-6-without-breaking-a-sweat

JavaScript
13
star
9

react-hooks-tips-only-the-pros-know-course

TypeScript
11
star
10

concurrent-rendering-adventures-in-react-18

TypeScript
11
star
11

react-hooks-tips-only-the-pros-know

The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components by a better understanding of how each React hook can be used.
TypeScript
11
star
12

Movies-GES

Movie management using GetEventStore
JavaScript
8
star
13

cra-template-mobx-state-tree-typescript

The MobX-state-tree TypeScript template for Create React App
TypeScript
7
star
14

use-formik-side-effects

Formik side effects hook and wrapper component
TypeScript
5
star
15

yup-faker

Yup schema with fake data generation
TypeScript
5
star
16

react-components-workshop

Advanced React Components Workshop
JavaScript
4
star
17

angular-docker-demo-dev

TypeScript
4
star
18

ParseLocals

Validate Visual FoxPro source code for missing variables
4
star
19

Techorama2014

JavaScript
4
star
20

react-hooks-tips-only-the-pros-know-course-complete

TypeScript
4
star
21

ts-react-2019-09-23

TypeScript
4
star
22

ts-react

TypeScript
3
star
23

lazy-routes

TypeScript
3
star
24

sveltekit-cypress-tdd

JavaScript
3
star
25

cypress-react-router

When using React Router Dom `cy.visit()` reloads the application from the server, use `cy.historyPush()` to navigate without reloading.
TypeScript
3
star
26

WebApi-Implicit-Grant-Flow

WebApi Implicit Grant Flow with Google
C#
2
star
27

reactadvanced-2023-ws

TypeScript
2
star
28

SDC-2014

SDC 2014 RavenDB Demo
C#
2
star
29

book-search

TypeScript
2
star
30

react-suspense-2020

TypeScript
2
star
31

AngularJSTest

AngularJS & TypeScript test project
JavaScript
2
star
32

mobx-fabric

TypeScript
1
star
33

Angular-2017-02

TypeScript
1
star
34

ddd333

TypeScript
1
star
35

dns-2019-01-26

React hooks demo code
JavaScript
1
star
36

dotnetflix-2019-2

TypeScript
1
star
37

Cedar.HttpCommandHandling

Middleware to handling commands over HTTP; typically used in CQRS applications.
C#
1
star
38

Advanced-AngularJS-2014-09-19

JavaScript
1
star
39

demo-2019-01-25

TypeScript
1
star
40

hooked-on-react

JavaScript
1
star
41

DM-Starting-AngularJS

DevelopMentor getting started with AnglarJS
JavaScript
1
star
42

ASP.NET-vNext-2015-02

ASP.NET vNext 2015-02 Demo code
C#
1
star
43

react-2019-09-09

JavaScript
1
star
44

LindugHTML5

LIDNUG Practical HTML5
JavaScript
1
star
45

ASP.NET-vNext-2015-03

ASP.NET 5 Beta 3 demos
C#
1
star
46

react-splitter

JavaScript
1
star
47

react-storybook-course-v5

JavaScript
1
star
48

AngularJS-ASP.NET

ASP.NET helpers for AngularJS
C#
1
star
49

ts-advanced

TypeScript
1
star
50

react-rotterdam-2020-01

React Suspense, not just for Alfred Hitchcock
TypeScript
1
star
51

demo-2019-01-24

Better React Components demo
JavaScript
1
star
52

mwd-2017-02-20

JavaScript
1
star
53

react-2019-07-15

React and TypeScript course examples
JavaScript
1
star
54

mobx-state-tree-template

Template for mobx-state-tree
TypeScript
1
star
55

reactnl-movies

JavaScript
1
star
56

DotNedAngularJS

JavaScript
1
star
57

React-2018-10-29

JavaScript
1
star
58

next-github-auth

TypeScript
1
star
59

react-snowpack-2020-07-01

Creating a React application using Snowpack
TypeScript
1
star
60

react-storybook-course

JavaScript
1
star
61

react-berlin-2023-ws

TypeScript
1
star
62

wax-brook

JavaScript
1
star