0

How should I handle an error that is thrown from a promise, in the catch block?

For instance,

try {

    // some other functions/code that can also throw error

    var promise = // a service that returns new Promise() object 

    promise.then(function(data) {
        //some business logic
    }, function(err) {
        throw new Error(err); // never gets caught in catch block
    });
} catch(error) {
    // do something with error
    console.log(error);
}

1) Is it possible to handle an error in try catch block thrown from promise?

2) Is there some better approach to handling common error?

rns
  • 1,047
  • 10
  • 25

1 Answers1

3

Promises work asynchronously, making them execute outside of the scope of the catch block you have here. This is why they have their own version of catch -

promise
.then(function(data) {
    //some business logic
    return anotherPromise;
 })
.then(function(data) {
    //some other business logic
 })
 // this keeps chaining as long as needed
.catch(function(err) {
    // You will get any thrown errors by any of the
    // chained 'then's here.
    // Deal with them here!
});

This is the recommended way.

hazardous
  • 10,627
  • 2
  • 40
  • 52
  • 1
    Even cooler you can recover in your catch (re-try AJAX request with `.catch` in service for example) so that the chain after doesn't need to be aborted. – ste2425 Jun 01 '16 at 07:52