javascript - Catching errors from callback handlers
问题描述
The perception is that if anything goes wrong within the promise, the catch handler is called but not in the following case when there's a callback involved.
Consider this scenario when an error occurs within a callback function and I assume the scope changes because the callback function is no longer under the PromiseCatcher's call stack and someone else is calling your callback. (Hope someone can correctly word this technically).
function query(sql, fn) {
setTimeout(fn, 1000);
}
function getUsers() {
return new Promise(function (resolve, reject) {
query("SELECT * FROM user", function(){ // callback crashes
console.log(b); // undefined var, crash + stack trace
});
});
}
getUsers().then(console.log, function(e){
console.log("caught in catch", e); // objective is to catch all errors here
})
Attempt 01 Fail
I am using a try-catch within promise:
function getUsers() {
return new Promise(function (resolve, reject) {
try {
query("SELECT * FROM user", function(){
console.log(b); // undefined variable
});
} catch(e) {
console.log("trying to catch error but no success", e)
reject(e);
}
});
}
Attempt 02 Success
I placed a try-catch within the callback method:
function getUsers() {
return new Promise(function (resolve, reject) {
query("SELECT * FROM user", function(){
try {
console.log(b); // undefined variable
} catch(e) {
console.log("caught finally")
reject(e); // have to manually reject it.
}
});
});
}
Just wondering if someone can give a better suggestion, it's a bit of a nuisance to define try catch within every callback method nested within promises I've.
My objective is to receive all errors in my catch
handler.
Response to proposed duplicate
I don't think this question is a duplicate of this one - I believe it is a totally different situation. (The linked answer talks about catching all rejections, whereas in this question I've an error occurring deeper inside a callback that fails to report).
My question deals with a scenario with a nested function inside a promise that has a callback. That callback is simply rogue.
Put simply, nested callback function to a function inside a promise fails to report and any error crashes the program with a stack trace.
解决方案
推荐阅读
- r - 识别导致 RStudio 中包构建失败的脚本
- java - How to read a Long number from application.yml
- c - 我正在尝试打印排序功能的迭代,它似乎有效,但有一些额外的数字
- android - 为什么我无法将数据添加到 Firestore
- python - 如何比较python中的两个文本文件?
- r - 使用 R 中的“fft()”进行卷积的非线性模型的错误曲线图
- kubernetes - Terraform kubernetes 集群通过 hetzner 云:lb 和服务器之间可能的循环依赖
- reactjs - 反应 onClick 因未知原因未触发
- ruby-on-rails - Rails:has_one 和 belongs_to 相同的模型
- angular - 将材质模块作为单独的模块导入时出错