Search code examples
node.jsunhandled-promise-rejection

Unhandled promise rejection inside a catch


I'm getting the following error inside a catch:

Blockquote UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originared either by throwing inside of an async function without a catch block, orby rejecting a promise which was not handled with .catch().

This is the code that invokes it:

http({
      method: 'post',
      url: config.uri,
      headers: headers,
      data: data
    }).then(function (response) {
      resolve(response.data);
    }).catch(function (error) {
      console.log(error.response.data);
      reject(error.response.data);
    });

The console.log call inside the catch reads: {status: 'ERROR', code: 'EMAIL_FAIL', message: 'Email fail to send' }

This code that calls the function:

router.post('/declaration', csrf, async function (req, res, next) {
    let reqId = generateReqId();
    const ref = reqId.split('-')[0];
   let data = buildSubmission(fakeSub, res.locals.locale.toUpperCase(), ref);
    let headers = { ref: data.ref, reqId: reqId };
    const response = await callAPI.submitApplication(data, headers);

    casaApp.endSession(req).then(() => {
      res.status(302).render('../views/pages/confirmation.njk');
    }).catch((err) => {
      console.log(err);
      res.status(302).render('../views/pages/exit-error.njk');
    });
  });

Why am I getting this? I want the code to return to the calling segment which will handle the problem. Any suggestions?


Solution

  • Your not catch errors from callAPI.submitApplication request:

    router.post('/declaration', csrf, async function (req, res, next) {
        const reqId = generateReqId();
        const ref = reqId.split('-')[0];
        const data = buildSubmission(fakeSub, res.locals.locale.toUpperCase(), ref);
        const headers = { ref: data.ref, reqId: reqId };
        try {
          const response = await callAPI.submitApplication(data, headers);
          await casaApp.endSession(req);
          res.status(302).render('../views/pages/confirmation.njk');
        } catch(e) {
          console.log(err);
          res.status(302).render('../views/pages/exit-error.njk');
        }
      });