more of an aspiration than a claim

Exception Handling - Promises vs Observables

A friend of mine was studying Promises in JavaScript. I mentioned how Promises swallow exceptions and continue execution by default.

I have recently been following RxJS and decided to knock up an example to find out how exceptions are handled differently in Promises versus Observables.

In the JS Bin below you will find the Promise swallows the exception thrown and we continue onto the Observable.

When subscribed to, the Observable throws an exception and the execution is halted. We never reach the last console log.

If you use the commented out catch statement for the Observable, then we can run to the last console log and exit cleanly.

So if you are going to use Promises, make sure you are vigilant and don’t let those errors slip through and bite you later on. Perhaps look into libraries like Bluebird that provide methods like onPossiblyUnhandledRejection to help you out. Or get on the Observables train ;)

var promise = new Promise((resolve) => {
  console.log("running promise");
  console.log("about to throw exception in promise");
  throw "Error Promise";
});

promise.then((x) => console.log(x));
console.log("NOTE: promise swallows exception and continues");

var source = Rx.Observable.create((observer) => {
  console.log("running observable");
  console.log("about to throw exception in observable");
  throw "Error Observable";
  observer.onNext("observable onNext");

  // uncomment below to catch observable exception
  // }).catch(function(e){
  //   console.log('Caught observable exception and returning it');
  //   return Rx.Observable.return(e);
});

//subscribe to observable to kick it off
source.subscribe(function (i) {
  console.log(i);
});

//shows we got to the end of the program. We never get here unless we catch the observable exception
console.log("last statement running");

Outputs:

"running promise"
"about to throw exception in promise"
"NOTE: promise swallows exception and continues"
"running observable"
"about to throw exception in observable"
X "Uncaught Error Observable (line 34)"

Removing the comments from the following lines:

// }).catch(function(e){
//   console.log('Caught observable exception and returning it');
//   return Rx.Observable.return(e);{% endcodeblock %}

Outputs:

"running promise"
"about to throw exception in promise"
"NOTE: promise swallows exception and continues"
"running observable"
"about to throw exception in observable"
"Caught observable exception and returning it"
"Error Observable"
"last statement running"

I don’t have a Pro account, but you can play with the JS Bin version.