Last active
July 15, 2017 13:32
-
-
Save niksumeiko/70288815f99639048d17 to your computer and use it in GitHub Desktop.
Catching errors thrown inside Nodejs promise
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
'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