Karamell Karamell - 16 days ago 5
Javascript Question

How do I catch inner exception?

I want to be able to catch an exception being thrown inside a promise, from outside the function of that promise. See the following code:

throwError = () => {
throw new Error("myError");
};


let iWantToCatchTheErrorThatThisOneThrows = () => {
return (new Promise( (resolve) => {
resolve()

}).then(() => {
(new Promise( (resolve, reject) => {
return throwError();
}));
return new Promise((resolve) => setTimeout(resolve, 1000));
})).catch((error) => {
//Never reaches here
console.log(error)
});
};

iWantToCatchTheErrorThatThisOneThrows().then(() => {
console.log("Quit gracefully");
}).catch((error) => {
//Never reaches here
console.log(error);
});


I can catch the inner error, but I can't throw it to end up where I want to (in the end), by adding a catch in the middle:

let iWantToCatchTheErrorThatThisOneThrows = () => {
return (new Promise( (resolve) => {
resolve()

}).then(() => {
(new Promise( (resolve, reject) => {
return throwError();
})).catch((error) => {
//Prints, but thrown error isn't bubbled anywhere
console.log(error);
throw new Error(error);
});
return new Promise((resolve) => setTimeout(resolve, 1000));
})).catch((error) => {
//Never reaches here
console.log(error)
});
};

iWantToCatchTheErrorThatThisOneThrows().then(() => {
console.log("Quit gracefully");
}).catch((error) => {
//Never reaches here
console.log(error);
});


All tests are run in Nodejs 7.1.0

Answer

I realised that my question is unreasonable, since I want to reject a promise that already is resolved. The problem is that I want to go on immediately from the promise, and not wait for it to resolve/throw. A more clear example would be like this:

writeToDatabase = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (hasPermissions) {
                resolve()
            } else {
                reject();
            }
        }, 1000)
    });
};


let iWantToCatchTheErrorThatThisOneThrows = () => {
    return new Promise((resolve) => {
        resolve()
    }).then(() => {
        //Don't want to wait for this to complete
        //but want to catch the error in later catch clauses
        //Unfortunately, this is unreasonable since I can't reject
        //a promise that might already have been resolved.
        //Therefore, refactor to have the same method to handle error
        writeToDatabase().catch(handleError); 

        return Promise.resolve();
    }).catch((error) => {
        //Will not catch the database error, since it's already resolved
        console.log('err', error)
    });
};

iWantToCatchTheErrorThatThisOneThrows().then(() => {
    console.log("Quit gracefully");
}).catch((error) => {
    // Will not catch the database error, since it's already resolved
    // Instead, we can reuse the same error handling function
    handleError(error);
});