exception handling, thrown errors, within promises

后端 未结 3 1298
梦谈多话
梦谈多话 2021-02-07 04:47

I am running external code as a 3rd party extension to a node.js service. The API methods return promises. A resolved promise means the action was carried out successfully, a f

3条回答
  •  情深已故
    2021-02-07 05:25

    Promise rejection is simply a from of failure abstraction. So are node-style callbacks (err, res) and exceptions. Since promises are asynchronous you can't use try-catch to actually catch anything, because errors a likely to happen not in the same tick of event loop.

    A quick example:

    function test(callback){
        throw 'error';
        callback(null);
    }
    
    try {
        test(function () {});
    } catch (e) {
        console.log('Caught: ' + e);
    }
    

    Here we can catch an error, as function is synchronous (though callback-based). Another:

    function test(callback){
        process.nextTick(function () {
            throw 'error';
            callback(null); 
        });
    }
    
    try {
        test(function () {});
    } catch (e) {
        console.log('Caught: ' + e);
    }
    

    Now we can't catch the error! The only option is to pass it in the callback:

    function test(callback){
        process.nextTick(function () {
            callback('error', null); 
        });
    }
    
    test(function (err, res) {
        if (err) return console.log('Caught: ' + err);
    });
    

    Now it's working just like in the first example.The same applies to promises: you can't use try-catch, so you use rejections for error-handling.

提交回复
热议问题