Nguyên Phương
Nguyên Phương

Reputation: 27

How to catch error in callback function JS?

I want to catch error in a callback function.

(async function(){
    function wait(ms){
        return new Promise(function(resolve, reject){
            setTimeout(resolve, ms);
        });
    }

    async function test(){
        while(true) {
            if (window.err){
                throw 'This is an error!';
            }
            await wait(500);
        }
    }

    
    try {
        console.log('running ...');

        window.err = false;
        setTimeout(function(){
            window.err = true;
        }, 1000);

        test();
    
        await wait(3000);
        console.log('end')
        console.log('done')
    }
    catch(err){
        // How do i catch error of "test" function in this
        console.log('end')
        console.log('error')
    }
})()

.................................................................................................................................................................................................... How do i catch error of test function in this? My englist is not good, help me pls! Thanks!

Upvotes: 0

Views: 596

Answers (2)

Yash Rami
Yash Rami

Reputation: 2327

if you want to catch the error from the test function you can try like this

(async function(){
    function wait(ms){
        return new Promise(function(resolve, reject){
            setTimeout(resolve, ms);
        });
    }

    async function test(){
      return new Promise((resolve, reject)  => {
       try {
          while(true) {
            if (window.err){
                throw 'This is an error!';
            }
            await wait(500);
            resolve();
          }
       } catch(err) {
             reject(err) // here we are catching the error and throw it back to the caller 
       }
      });
    }

    
    try {
        console.log('running ...');

        window.err = false;
        setTimeout(function(){
            window.err = true;
        }, 1000);

       try {
         await test();
       } catch (err) {
         console.log(err) // here we get the error from the test
       }

    
        await wait(3000);
        console.log('end')
        console.log('done')
    }
    catch(err){
        // How do i catch error of "test" function in this
        console.log('end')
        console.log('error')
    }
})()

I hope it helps you out

Upvotes: 0

leodriesch
leodriesch

Reputation: 5780

test is an asynchronous function, if you call it without awaiting it the errors will be ignored.

Instead of test() use await test().

Or if you don't want to await it and just be notified when an error happens, you can use Promise.catch:

test().catch(err => {
  // Handle the error in some way
  console.error(err)
}) 

Upvotes: 1

Related Questions