下面的代码解释了主异步进程中的两个异步代码。我的问题是“userController.insertUser” - 捕获了一些错误但该错误无法抛出主要捕获
DataMiddleware.DataValidate(Object).then((middlewareSuccess) => {
switch (true) {
case ((tableName === "users") && (method === "CREATE")):
userController.insertUser(Object).then(()=> {
...
}).catch((err) => {
return err
})
break;
case ((tableName === "users") && (method === "BATCH")):
userController.updateUser(Object).then(()=> {
...
}).catch((err) => {
return err
})
break;
}
}).catch((err) => {
console.log("main error",err)
})
如何正确捕捉?
答案 0 :(得分:1)
有两种方法可以处理嵌套的promise错误。
1)将其捕获到嵌套的promise中并将其抛给父
const DataMiddleware = {
DataValidate: sinon.fake.resolves("value")
};
const userController = {
insertUser: sinon.fake.rejects("insertUser erroorr"),
updateUser: sinon.fake.rejects("updateUser erroorr")
};
const tableName = "users",
method = "CREATE";
DataMiddleware.DataValidate()
.then(middlewareSuccess => {
switch (true) {
case tableName === "users" && method === "CREATE":
return userController.insertUser()
.catch(err => {
console.log("nested catch handler " + err);
throw err;
});
}
})
.catch(err => {
console.log("main error " + err);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/5.0.1/sinon.js"></script>
2)返回承诺并让父母处理发生的任何错误
const DataMiddleware = {
DataValidate: sinon.fake.resolves("value")
};
const userController = {
insertUser: sinon.fake.rejects("insertUser erroorr"),
updateUser: sinon.fake.rejects("updateUser erroorr")
};
const tableName = "users",
method = "CREATE";
DataMiddleware.DataValidate()
.then(middlewareSuccess => {
switch (true) {
case tableName === "users" && method === "CREATE":
return userController.insertUser()
}
})
.catch(err => {
console.log("main error " + err);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/5.0.1/sinon.js"></script>
这里的重点是承诺链。您从另一个返回新的承诺,第一个catch
处理程序仍然有效。