0

My class constructor calls a promise that connects to a service. How do I trap an error if the connection fails? My call to create the class instance is wrapped in a try catch block, but it doesn't get the error from the promise. Like this...

const client = require('aService')

try{let s = new Service()}
catch(e){console.log(`instance error ${e}`)

class Service{

    constructor(){
      this.connection = client.login()
         .then(){
            ...
          }
         .catch(e=>{
            console.log(`promise error ${e}`
            return e
           })
    }

The console will log "promise error" but not "instance error", which I need so that I can cleanly handle the class instance failing.

Many thanks

Kittovski
  • 177
  • 3
  • 16

1 Answers1

0

The Promise is assigned to this.connection, but you're .catching the error in the constructor. Better to catch the error only when you can do something with it - that is, in the consumer of the Service outside. So, just move the .catch from the constructor to right below where you create the service:

const client = require('aService')

class Service {
  constructor() {
    this.connection = client.login()
      .then(() => {
        // ...
      });
  }
}


let s = new Service()
s.connection.catch((e) => {
  console.log(`connection error ${e}`)
});

Or use await with try/catch:

const client = require('aService')

class Service {
  constructor() {
    this.connection = client.login()
      .then(() => {
      // ...
    });
  }
}


(async () => {
  let s = new Service()
  try {
    await s.connection;
    // connection done
  } catch(e) {
    console.log(`connection error ${e}`)
  }
})();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320