Amir Ali
Amir Ali

Reputation: 225

How to avoid UnhandledPromiseRejectionWarning in Node

I have to test some JSON/RPC based web app with different combinations of values. Some values cause error (as expected). Now I just want to continue my testing with saving of error/exception (throws during execution). For example as per given code

    const abcWeb = require('abc-web');
const abcWeb = new abcWeb('http://testnet-jsonrpc.abc-xyz.org:12537');

const abTx = require('abc-transaction');
var n = 12;
var gp = 10;
var gl = 21000;
var to = '5989d50787787b7e7';
var value = 70;
var limit = 4;
var i=1;
while (i<limit){

  try{
const tx = new abTx({
    n: n,
    gp: gp,
    gl:gl , 
    to: to, 
    value:value ,
  });

    abTx.sign(Buffer.from('8f2016c58e898238dd5b4e00', 'hex'));
    abcWeb.abx.sendSignedTransaction('0x' + tx.serialize().toString('hex'));
    console.log(abTx);

  } catch (exception) {
    var message = exception.message;
    console.log(message);
    continue;

  }
  finally {
    i++;
    n +=1;
    gp +=1;
    gl +=1;
    abcWeb.abx.getENumber().then(console.log);
  }
}

But when UnhandledPromiseRejectionWarning error occurred, node will stop execution. Is it possible to bypass UnhandledPromiseRejectionWarning error ? How to make a loop of for such errors to skip ? UnhandledPromiseRejectionWarning error normally comes after sign function and/or sendSignedTransaction.. I just want to bypass it.

Upvotes: 0

Views: 774

Answers (2)

Amit Kumawat
Amit Kumawat

Reputation: 139

You can add an handler for the unhandledRejection event:

process.on('unhandledRejection', error => {
  // handle error ... or don't
});

See https://nodejs.org/api/process.html#process_event_unhandledrejection
and https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event

Upvotes: 2

Tuan Anh Tran
Tuan Anh Tran

Reputation: 7267

catch (err) cannot catch UnhandledPromiseRejectionWarning error from Promise when you use .then(). You can either change it to await myPromise() style or you can .catch a promise.

Example: this will throw error UnhandledPromiseRejectionWarning

async function test() {
    throw new Error()
}

;(async function main() {
    try {
        test().then(console.log)
    } catch (err) {
        console.log('caught it', err);
    }
})()

This will not:

async function test() {
    throw new Error()
}

;(async function main() {
    try {
        test().then(console.log)
            .catch(() => {})
    } catch (err) {
        console.log('caught it', err);
    }
})()

This also will not

async function test() {
    throw new Error()
}

;(async function main() {
    try {
        await test()
    } catch (err) {
        console.log('caught it', err);
    }
})()

Upvotes: 0

Related Questions