admin管理员组文章数量:1326493
let p be a promise we can do
p
.then(f1)
.then(f2)
.then(f3)
.catch(f4)
now in catch, error can be thrown from any of f1,f2,f3 or even p rejected
now what should be the proper way to handle errors in f4(or in catch) , as errors thrown above can be of different types, Can multiple if else be avoided in f4 ?
let p be a promise we can do
p
.then(f1)
.then(f2)
.then(f3)
.catch(f4)
now in catch, error can be thrown from any of f1,f2,f3 or even p rejected
now what should be the proper way to handle errors in f4(or in catch) , as errors thrown above can be of different types, Can multiple if else be avoided in f4 ?
Share Improve this question edited Sep 11, 2017 at 16:45 ashish singh asked Sep 11, 2017 at 16:38 ashish singhashish singh 6,9142 gold badges17 silver badges40 bronze badges3 Answers
Reset to default 3You can define you own custom error. For example :
function CustomError(errorText){
this.error = errorText;
}
Modify your functions. Add catch block for each Promise returned from function:
function p(){
return new Promise(function(resolve, reject){
//Your functionality here
})
.catch(function(error){
Promise.reject(new CustomError('f1')));
})
}
And so on: f2, f3, f4
And your catch block will be:
.catch((err) => {
if(err instanceof CustomError){
HandleCustomError(err);
} else {
//Some another error is happen
}
})
And you custom error handler will be something like that:
function HandleCustomError(customError){
switch(customError.error){
case 'f1':
//handle f1
break;
case 'f2':
//handle f2
break;
...
}
}
Just define an additional catch
callback:
p
.then(f1)
.then(f2)
.then(f3)
.catch(err => {
if (/* is expected error */) {
console.log(err);
return;
}
throw new Error('Unexpected error');
})
.catch(err => ...)
By catching error in the Promise that is rejected, you won't need to worry about the different types of error in the final catch block, and your code should bee more readable (in the sense that it's easier to see that each catch block handles the appropriate rejection).
I also remend, if it's possible in your case, to use async/await. Rejected promises are equivalent to thrown Errors in this syntax. Instead of using a lot of chained Promises, the logic of "each catch block in the right place" is more direct and should make bugs easier to be spotted.
try {
const v1 = await f1();
} catch (err) {
// Process err
}
try {
const v2 = await f2(v1);
} catch (err) {
// Process err
}
本文标签: How to handle errors from multiple then in catch of javascript promisesStack Overflow
版权声明:本文标题:How to handle errors from multiple then in catch of javascript promises? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742202557a2432231.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论