Skip to content

Instantly share code, notes, and snippets.

@joepie91
Last active June 25, 2023 09:03
Show Gist options
  • Save joepie91/b0c8f9a9309f5398080eab84482d58a4 to your computer and use it in GitHub Desktop.
Save joepie91/b0c8f9a9309f5398080eab84482d58a4 to your computer and use it in GitHub Desktop.
Errors 'bubbling up the chain' with Promises, and catching specific kinds of errors (with Bluebird)

Promise.try is explained here.

const Promise = require("bluebird");
function makeRequest(url) {
return Promise.try(() => {
return bhttp.get(url); // Whether an error occurs here...
}).then((response) => {
return response.body; // ... or here...
}).catch({name: "TypeError"}, (err) => { // ... and as long as it's not a TypeError in the previous two places...
console.log("A wild TypeError appears!", err);
process.exit(1);
});
}
function makeManyRequests(urls) {
return Promise.try(() => {
if (urls.length === 0) {
throw new Error("Must specify at least one URL"); // ... or here (even if it's a TypeError!) ...
} else {
return urls;
}
}).map((url) => {
return makeRequest(url);
});
}
function doMyThing() {
return Promise.try(() => {
return makeManyRequests([
"http://google.com/",
"http://bing.com/",
"http://yahoo.com"
]);
}).catch((err) => {
console.log("Oh noes!", err); // ... it will always end up here, as long as it wasn't caught by our previous .catch.
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment