07_05_GuyT
07_05_GuyT

Reputation: 2887

Promise reject error - Unhandled rejection Error: closed

I use the following code to check some app port currenlty its working but I got error in the third else statement

Unhandled rejection Error: Port is not open

How can I handle that ? I use bluebird

checkPortStatus: function(port, host){
  return new Promise((resolve, reject) => {
    portscanner.checkPortStatus(port, host, function(error, status) {
      if(error)
        reject(error);
      else if(status === 'open')
        resolve(status);
      else
        reject(new Error('Port is not open'));
    });
  });
},

Upvotes: 0

Views: 1508

Answers (2)

BaldEagle
BaldEagle

Reputation: 1018

Attributes of the code calling checkPortStatus cause the unhandled exception.

That code might look like

somePromiseFunction()
.then(checkPortStatus(port, host))
.then(someOtherPromiseFunction())

It would (minimally) "handle" the exception if it looked more like

somePromiseFunction()
.then(checkPortStatus(port, host))
.catch(function(error) {
  console.log(error.message);
})
.then(someOtherPromiseFunction()

There's trouble in your code in this aspect: When using resolve and reject, it's also necessary to use return. So instead of resolve(), use return resolve(); same with reject.

A side note, in case it helps: Once you add the returns I mention, each of the else statements in your code is immediately preceded by a return. You can delete the else statements.

Good luck!

Upvotes: 1

robertklep
robertklep

Reputation: 203241

Eventually, you need to handle rejected promises, for instance using a .catch():

obj.checkPortStatus(port, host).then((status) => {
  ...
}).catch((err) => {
  // handle the error here...
});

Upvotes: 1

Related Questions