[ES2024] Improve Application-wide Error Handling rethrowing JavaScript Error with the Error Cause

The new cause data property that you can add to a thrown Error can be used to retain access to the original error caught in a promise rejection.

 

const sendLog = (...args) => console.log(...args);

async function fetchStuff() {
    await fetch('http://doesnt.exist/stuff')
        .catch(err => {
            sendLog(err);
            throw new Error('Loading stuff failed', { cause: err });
        });
}

fetchStuff()
    .catch(err => {
        console.log(err);
        console.log(err.cause);
    });

posted @ 2024-05-22 14:37  Zhentiw  阅读(4)  评论(0编辑  收藏  举报