0

I created a custom typescript error, which based on several sources seems to go like this:

export class Exception extends Error {

    constructor(public message: string) {
        super(message);
        this.name = 'Exception';
        this.message = message;
        this.stack = (<any>new Error()).stack;
    }
    toString() {
        return this.name + ': ' + this.message;
    }
}

export class SpecificException extends Exception {

}

In my code I then throw this using a simple:

 throw new SpecificException('foo');

And elsewhere I catch it:

catch (e) {
  var t1 = Object.getPrototypeOf(e);
  var t2 = SpecificException.prototype;

  if (e instanceof SpecificException) {
    console.log("as expected");
  }
  else {
     console.log("not as expected");
  }
}

This code prints "not as expected". Any ideas why?

Later edit

As @basarat points out bellow, the error is of the expected type. Upon further investigation I realised that this was due to a module duplication having to do with my environment, possibly because of using mocha in watch mode.

1
  • 2
    Are you sure? For me both e instanceof Exception and e instanceof SpecificException are true. Commented Jun 14, 2016 at 21:39

1 Answer 1

5

Ran the following code:

declare global {
    interface Error {
        stack: any;
    } 
}
class Exception extends Error {

    constructor(public message: string) {
        super(message);
        this.name = 'Exception';
        this.message = message;
        this.stack = (<any>new Error()).stack;
    }
    toString() {
        return this.name + ': ' + this.message;
    }
}
class SpecificException extends Exception {

}

try {
  throw new SpecificException('foo');   
}
catch (e) {
  var t1 = Object.getPrototypeOf(e);
  var t2 = SpecificException.prototype;

  if (e instanceof SpecificException) {
    console.log("as expected");
  }
  else {
     console.log("not as expected");
  }
}

Got the desired outcome:

as expected

So there is no bug posted in the asked question 🌹

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.