promise-reject-fallback

Add a rejection fallback handler to a Promise if no one handles it

Usage no npm install needed!

<script type="module">
  import promiseRejectFallback from 'https://cdn.skypack.dev/promise-reject-fallback';
</script>

README

Promise Reject Fallback

Build Status codecov Greenkeeper badge

npm install promise-reject-fallback

yarn add promise-reject-fallback

Use Case

You want to add a rejection handler to a Promise but you only want it to run if the consumer doesn't handle your promise rejection.

Example:

import axios from 'axios'

const fetchPosts = () => axios.get('/posts').catch(error => alert(error))

// Page 1
fetchPosts.then(posts => console.log(posts))

// Page 2
fetchPosts.then(posts => console.log(posts)).catch(error => showDialog(error))

You have a error handler on fetchPosts to globally handle an error, in this case we use alert. This is great for Page 1 because we have a generic way of handling and displaying errors! This is not great for Page 2 because now we have duplicated error handling, our catch handler in fetchPosts handles the rejection, but so does Page 2.

The withFallback will decorate your Promise and allow you to add a fallback rejection handler only if one wasn't added later in the chain.

import axios from 'axios'
import { withFallback } from 'promise-reject-fallback'

const fetchPosts = () =>
    withFallback(() => axios.get('/posts'), error => alert(error))

// Page 1, alert Error!
fetchPosts.then(posts => console.log(posts))

// Page 2, dialog with Error!
fetchPosts.then(posts => console.log(posts)).catch(error => showDialog(error))