Skip to content

Instantly share code, notes, and snippets.

@fson
Last active September 18, 2016 19:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fson/1b521bb62d2e2addfd61f49a604111a9 to your computer and use it in GitHub Desktop.
Save fson/1b521bb62d2e2addfd61f49a604111a9 to your computer and use it in GitHub Desktop.
Promise error handling with the Either pattern (disjunction)
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