5
export class InvalidCredentialsError extends Error {
  constructor(msg) {
    super(msg);
    this.message = msg;
    this.name = 'InvalidCredentialsError';
  }
}

As you can see above, I'm writing InvalidCredentialsError twice. Is there a way to somehow get the class name already in the constructor method and set it? Or does the object have to be instantiated?

basickarl
  • 31,830
  • 51
  • 195
  • 300

1 Answers1

7

In browsers with native ES6 class support, this.constructor.name will display the InvalidCredentialsError. If you transpile the code with Babel it will show Error.

Without Babel (use on Chrome or another browser that supports class):

class InvalidCredentialsError extends Error {
  constructor(msg) {
    super(msg);
    console.log(this.constructor.name);
    this.message = msg;
    this.name = 'InvalidCredentialsError';
  }
}

const instance = new InvalidCredentialsError('message');

With Babel:

class InvalidCredentialsError extends Error {
  constructor(msg) {
    super(msg);
    console.log(this.constructor.name);
    this.message = msg;
    this.name = 'InvalidCredentialsError';
  }
}

const instance = new InvalidCredentialsError('message');
Ori Drori
  • 166,183
  • 27
  • 198
  • 186