Skip to content

Instantly share code, notes, and snippets.

@niksumeiko
Last active July 15, 2017 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save niksumeiko/70288815f99639048d17 to your computer and use it in GitHub Desktop.
Save niksumeiko/70288815f99639048d17 to your computer and use it in GitHub Desktop.
Catching errors thrown inside Nodejs promise
'use strict';
var Promise = require('promise');
/** @desc A function that returns a promise with an error-prone code. */
function build() {
return new Promise(function(fulfill, reject) {
// This line is going to throw an error forcing JavaScript
// interpreter to stop, and promise fulfillment on the
// next line is not going to be reached.
whatever.error = 'error';
fulfill();
});
}
build().then(function(result) {
// This is line is not going to be reached, because promise catched
// an error before fulfillment.
console.log(result);
}, function(error) {
// When program throws an error inside a promise, program does
// not exit (like it would without a promise or without try/catch),
// but it rejects the promise automatically, executing `reject`
// callback with an Error as the only argument.
console.error(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment