Rethrowing error in promise catch

前端 未结 6 1766
迷失自我
迷失自我 2021-01-30 02:59

I found the following code in a tutorial:

promise.then(function(result){
    //some code
}).catch(function(error) {
    throw(error);
});

I\'m

6条回答
  •  一向
    一向 (楼主)
    2021-01-30 03:18

    Both .then() and .catch() methods return Promises, and if you throw an Exception in either handler, the returned promise is rejected and the Exception will be caught in the next reject handler.

    In the following code, we throw an exception in the first .catch(), which is caught in the second .catch() :

    new Promise((resolve, reject) => {
        console.log('Initial');
    
        resolve();
    })
    .then(() => {
        throw new Error('Something failed');
            
        console.log('Do this'); // Never reached
    })
    .catch(() => {
        console.log('Something failed');
        throw new Error('Something failed again');
    })
    .catch((error) => {
        console.log('Final error : ', error.message);
    });

    The second .catch() returns a Promised that is fulfilled, the .then() handler can be called :

    new Promise((resolve, reject) => {
        console.log('Initial');
    
        resolve();
    })
    .then(() => {
        throw new Error('Something failed');
            
        console.log('Do this'); // Never reached
    })
    .catch(() => {
        console.log('Something failed');
        throw new Error('Something failed again');
    })
    .catch((error) => {
        console.log('Final error : ', error.message);
    })
    .then(() => {
        console.log('Show this message whatever happened before');
    });

    Useful reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#Chaining_after_a_catch

    Hope this helps!

提交回复
热议问题