Dean Ambrose
Dean Ambrose

Reputation: 193

Unable to throw error in angular js promise

I have an as promise as :

try {    
   myPromise().then(function(){
       console.log("ok");
     }, function(err) { throw err; });
} catch(e) {
    console.log("error");
}

now my control goes to the function(err) and it throws the error but the error is not caught in catch().

Upvotes: 0

Views: 233

Answers (2)

Pavel Agarkov
Pavel Agarkov

Reputation: 3783

You have two options:

1) Use Promise.catch:

myPromise().then(function(){
       console.log("ok");
     }, function(err) { throw err; })
     .catch(function(err) { console.log("error"); });

2) If you have transpiler use async/await:

async function parentFunction() {
  try {
    await myPromise();
    console.log("ok");
  }
  catch (e) {
    console.log("error");
  }
}

Upvotes: 1

Steve Danner
Steve Danner

Reputation: 22158

Because promises are asynchronous, flow control doesn't work the way you're thinking it will. Your try...catch block is outside of the promise initialization code, and once it initializes the promise, it's done. So the try...catch block is only handling promise initialization in the code above. If the promise is rejected/errored (as you say it is doing in your code), the error function will fire within the error function closure only.

Consider a common error handler or you can refactor your try...catch block to be within the closure.

Here's the code with the common error handler:

try {    
   myPromise().then(function(){
       console.log("ok");
     }, function(err) { 
       errHandler(err); 
     });
} catch(e) {
    errHandler(e);
}


function errHandler(err) {
   console.log("error");
}

Upvotes: 1

Related Questions