skip to Main Content

The problem I am facing is that somewhere in the code I am working with there is an error that I cannot catch. The simplest example of this would be the code below:

try {
    new Promise((res, rej) => rej(new Error('You cannot catch me. Haha')));
} catch (err) {
    conosle.error(err);
}

Result in the console

I don’t want to alter the code much. I want to be able to catch and ignore some errors like that. I am trying to replace Promise by wrapping it so that i can catch all errors of that sort.

I have tried asking ChatGPT and it doesn’t help much, so Googling will most probably not help also.

2

Answers


  1. Chosen as BEST ANSWER

    After some fighting and effort I came up with this solution:

    const P = window.Promise;
    
    const errorIgnorer = (err) => {
        if (err?.message?.includes('The play() request was interrupted by a call to pause()')
            || err?.message?.includes('Already in offline state')
            || err?.message?.includes('Pending connection was cancelled due to a disconnect request')) {
            return;
        }
        throw err;
    };
    
    function PromiseTemp(cb) {
        let promise = new P(cb);
    
        promise = promise.catch(errorIgnorer);
    
        function then(onFulfilled, onRejected) {
            const temp = P
                .prototype
                .then
                .call(
                    this,
                    onFulfilled,
                    onRejected
                )
                .catch(errorIgnorer);
    
            temp.then = then;
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            temp.catch = catchFn;
    
            return temp;
        }
    
        function catchFn(onRejected) {
            const temp = then.call(this, null, onRejected);
            temp.then = then;
            temp.catch = catchFn;
            return temp;
        }
    
        promise.then = then;
        promise.catch = catchFn;
    
        return promise;
    }
    
    Object.setPrototypeOf(PromiseTemp.prototype, P.prototype);
    Object.setPrototypeOf(PromiseTemp, P);
    
    window['Promise'] = PromiseTemp as any;
    

    This solution catches all errors generated inside of promises and ignores errors that errorIgnorer function "filters".


  2. Promises have their own catch clause. You can catch it through that.

    try {
      new Promise((res, rej) => rej(new Error('You cannot catch me. Haha')))
                 .catch(error => console.log("caught"));
    } catch (err) {
        conosle.error(err);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search