Can't handle promise rejection

Viewed 35
function sendPushNotification(subscription, urlEncodedData){
  try {
    webpush.sendNotification(subscription, urlEncodedData);
  } catch (err){
    console.log('err');
    console.log(err);
  }
}

This doesn't catch the error, it is still considered an 'unhandledRejection'. Why?

1 Answers

If you're calling an async function, or a function that returns a Promise then you need to sequence things properly:

async function sendPushNotification(subscription, urlEncodedData){
  try {
    await webpush.sendNotification(subscription, urlEncodedData);
  } catch (err){
    console.log('err');
    console.log(err);
  }
}

Here await will capture any response. An error condition that will manifest as an exception.

Note that this makes sendPushNotification() return a Promise so you will have to treat it as asynchronous. This means the caller needs to await as well, and that may have impacts up the call chain depending on your sequencing requirements.

Related