Reputation: 3446
I feel like this should be easy, but I've been struggling for a while on it.
I have code that looks like this (obviously this is a simplified example).
getPromise(param1, param2)
.then(function (results) {
// do something that causes an error:
var err1 = new Error()
throw err1;
})
.then(function (results) {
getAnotherPromise(param1)
.then(function (res) {
// do something else that might cause an error:
var err2 = new Error()
throw err2;
})
})
.then(function (results) {
// deal with the results of above code
})
.fail(function (error) {
// handle error
})
The issue is that err2
never causes the .fail
handler to be called. err1
is dealt with as expected, but err2
just disappears. I've tried adding another .fail
handler after the .then
responsible for generating err2
that just re-throws err2
, but that doesn't change anything.
How can I write one error handler that deals with both err1
and err2
?
Upvotes: 1
Views: 711
Reputation: 51480
Q
can't handle nested promise unless you return
it. So, your code should look like this:
getPromise(param1, param2).then(function (results) {
// do something that causes an error:
throw new Error('error 1');
}).then(function (results) {
return getAnotherPromise(param1).then(function (res) {
// do something else that might cause an error:
throw new Error('error 2');
})
}).then(function (results) {
// deal with the results of above code
}).fail(function (error) {
// handle error
})
Actually, promise values are propogated as well as errors, so you may write your code in the following way:
getPromise(param1, param2).then(function (results) {
// do something that causes an error:
throw new Error('error 1');
}).then(function (results) {
return getAnotherPromise(param1)
}).then(function (res) {
// do something else that might cause an error:
throw new Error('error 2');
}).then(function (results) {
// deal with the results of above code
}).fail(function (error) {
// handle error
})
Upvotes: 3