Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof custom error class returning false [duplicate]

Tags:

javascript

Why does this result in false?

'use strict';

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

const err = new InvalidCredentialsError('');

console.log(err instanceof InvalidCredentialsError);

But this returns true:

console.log(err instanceof Error);

enter image description here

like image 797
basickarl Avatar asked Jan 18 '17 12:01

basickarl


1 Answers

This works...you need to construct an instance of your type, then instanceof will return whether your object is indeed an instance of that type.

'use strict';

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

var err = new InvalidCredentialsError("Hello, world!");

console.log(err instanceof InvalidCredentialsError); // true

Note const errClass = InvalidCredentialsError; will just create an alias for your type, so you could do this...

var err = new errClass("Hello, alias");
console.log(err instanceof errClass); // true
like image 143
Matthew Layton Avatar answered Sep 29 '22 12:09

Matthew Layton