Promises - error callback vs. catch Promises - error callback vs. catch angularjs angularjs

Promises - error callback vs. catch


Both will achieve the same thing, except the second one might run errorHandler three times (instead of just once). You are correct that it brings some code duplication, but it also allows you to treat whatever error happened and continue with your chain:

function errorHandler(err) {  //log error, continue  return $q.resolve('default value or something');}doSomething0()  .then(doSomething1, errorHandler)  .then(doSomething2, errorHandler)  .then(doSomething3, errorHandler);


Let's have a look at the first sample:

doSomething0()    .then(doSomething1, errorHandler)    .then(doSomething2, errorHandler)    .then(doSomething3, errorHandler);// I've represented functions invocations as if they were synchronous to simplify the example to focus on the error handling// The above sample is in a way "equivalent" totry {    // doSomething0()    try {        // doSomething1()        try {          // doSomething2()        } catch(e0) {           // handle error        }      } catch(e1) {         // handle error    }} catch(e2) {     // handle error}// doSomething3()

But if an exception happens in the doSomething3 handler, it won't be handled.

Ok, let's have a look at the second sample:

doSomething0()    .then(doSomething1)    .then(doSomething2)    .then(doSomething3)    .catch(function (err) {        // do something with `err`    });// I've represented functions invocations as if they were synchronous to simplify the example to focus on the error handling// The above sample is in a way "equivalent" totry {    // doSomething0()    // doSomething1()    // doSomething2()    // doSomething3()}catch(e) {    // Catch 'em all    console.log(e)}