我正在使用axios响应拦截器,并且取消请求后,需要断开承诺链。我不想为我的应用程序中的所有请求添加已取消请求的错误检查。我已经尝试过bluebird,但似乎只是承诺取消,而不是断链。我必须在第一个陷阱中处理错误。此图一般显示了该问题。然后,最新和捕获位于不同文件中。
Promise
.then((response) => {
)
.catch((error) => {
// break promise here
})
.then((response) => {
// skip
// I don't want any extra checks here!
)
.catch((error) => {
// skip
// I don't want any extra checks here!
})
仅在末尾仅保留一个catch块即可收集您的promise链触发的所有错误。
如果一个诺言抛出了链中的以下内容,则不执行
Promise
.then((response) => {
)
.then((response) => {
// skip
// I don't want any extra checks here!
)
.catch((error) => {
// skip
// I don't want any extra checks here!
})
另一个选择是抛出一个自定义错误,该错误可以在结尾的单个catch
块中捕获,如下所示:
const errorHandler = require('path/to/handler')
class ProcessingError1 extends Error {
constructor(message) {
super(message);
this.name = "ProcessingError1";
}
}
class ProcessingError2 extends Error {
constructor(message) {
this.message = message;
this.name = "ProcessingError2";
}
}
const process1 = async () => {
throw new ProcessingError1("Somethign went wrong");
};
const process2 = async () => {
return { some: "process" };
};
const someApiCall = async () => ({ some: "response" });
someApiCall()
.then(process1)
.then(process2) // process2 is not run if process1 throws an error
.catch(errorHandler);
// ErrorHandler.js
module.exports = e => {
if (e instanceof ProcessingError1) {
// handle error thrown from process1
}
else if (e instanceof ProcessingError2) {
// handle error thrown from process2
}
else {
// handle other errors as needed..
}
}