jmrueda
jmrueda

Reputation: 1428

UnhandledPromiseRejectionWarning in non async function in Node / Express

I am having some issues understanding this error. I have a function called getDeliveryDate() that is called from an endpoint. This function seems non async function, but I am getting an unhandled promise error:

// Deadlines increments are in minutes
function getDeliveryDate(
  inputDate,
  normalDeadline,
  fastDeadline,
  fastDelivery
) {
  var deliveryDate = new Date();

  try {
    !fastDelivery
      ? deliveryDate.setTime(inputDate + normalDeadline * 60 * 1000)
      : deliveryDate.setTime(inputDate + fastDeadline * 60 * 1000);

    return deliveryDate;
  } catch (error) {
    console.log("getDeliveryDate error:".error, error);//  <-- this line is okey, I am using colors library
  }

And this is where is call getDeliveryDate

...
     try {
              blockFields.finishDate = getDeliveryDate( // <-- the call
                Date.now(),
                req.body.blockOptions.deadline,
                req.body.blockOptions.fastDeadline,
                req.body.blockOptions.fastDelivery
              );
            } catch (error) {
              console.log("getDeliveryDate error".error, error); // <-- this line is okey, I am using colors library
            }
...

What I am missing? Is getDeliveryDate an async function? How can I properly handle its errors?

UPDATE

I was using a variable that I later modified, so no longer existed. After correcting the error, I am still unsure about how to catch an error for this function.

Now everything is working, but if I enter a wrong variable I am still not catching the error and getting this error (i.e. if I enter a wrong finishDate value):

(node:50620) UnhandledPromiseRejectionWarning: ValidationError: blocks validation failed: finishDate: Cast to Date failed for value "Invalid Date" at path "finishDate"

Why my catch(error) is not working?

Upvotes: 0

Views: 82

Answers (1)

tagyoureit
tagyoureit

Reputation: 1286

Add --trace-warnings to your arguments for launching Node. It should show you a stack trace of the unhandled errors.

However, it does look like this line console.log("getDeliveryDate error".error, error); may be the culprit. You have an error in the catch block but there is nothing to catch that error.

Upvotes: 1

Related Questions