首页 > 解决方案 > 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.

标签: javascriptnode.jserror-handling

解决方案


推荐阅读