【发布时间】:2019-03-20 17:30:23
【问题描述】:
我有一个可以处理通过 Web API 执行的 HTTP 请求的承诺:
promise = promise.then(r => {
// ...
}, error => {
if (error.status == 404) {
// Here I can fix an error and continue properly
} else {
// Here the error should be propagated further in the promise
}
}
// later in the code:
promise.catch(r => { /* More error handling */ } );
在代码的后面,这个承诺被链接到更多的错误检查。
如果出现 404 错误,我实际上可以“修复”问题,并且我不希望其他处理程序触发。在这种情况下,我宁愿让诺言成功。我该怎么做?
更多代码来更深入地解释我的案例:
refresh() {
this.refreshAsync().catch(r => {
// Show error to the user.
notifications.showError("Unexpected error happened");
});
}
async refreshAsync() {
// Here goes a lot of vue-resource calls to gather the necessary data for a view. They are chained with `await`. Only one of them:
await this.$http.get(url).then(r => {
this.data = r.data;
}, error => {
// 404 is actually a legit response for API to return, so the user notification above should not be shown
if (error.status == 404) {
// handle successfully
} else {
// propagate an error, so the handler above could show a warning to the user.
}
});
}
【问题讨论】:
-
您的
promise是如何声明的?您必须检测 404 错误并调用reject()。 -
您能告诉我们您打算如何处理成功案例吗?
-
@Zenoo 这是
vue-resource返回的承诺。我无法控制声明 -
@AseemUpadhyay 请查看更新
-
您是否尝试过使用interceptor?
标签: javascript typescript vue.js promise