Last active
September 18, 2016 19:01
-
-
Save fson/1b521bb62d2e2addfd61f49a604111a9 to your computer and use it in GitHub Desktop.
Promise error handling with the Either pattern (disjunction)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Failure, Success } from 'data.validation'; | |
// Report unhandled promise rejections (bugs) | |
window.onunhandledrejection = (event) => { | |
// Raven.captureException(event.reason); | |
console.error('Unhandled rejection:', event.reason); | |
}; | |
function fetchRepo(name) { | |
return fetch(`https://api.github.com/repos/${name}`).then((response) => | |
response.json().then((data) => | |
response.ok ? Success(data) : Failure(data) | |
) | |
); | |
} | |
function getStars(name) { | |
fetchRepo(name).then((result) => { | |
const message = result.fold( | |
(error) => `Fetching '${name}' failed: ${error.message}`, | |
(repo) => `${name}: ${repo.stargazers_count} stars` | |
); | |
console.log(message); | |
}); | |
} | |
getStars('babel/babel'); | |
getStars('facebook/react'); | |
getStars('fson/repo_does_not_exist'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment