2

Let's say I have an abstract class such as this.

abstract class AppException extends Error {
  // constructor, functions, whatever   
}

Let's also say I have a class like

class NotFoundException extends AppException {
}

Now I have an object error of type Error in a random function. I passed an instance of NotFoundException to the function.

In the error, if I try to do

if (error instanceof AppException) {
return something;
} 
return otherThing;

The expression in the if statement returns false and it returns otherThing when I'm sure I've passed NotFoundException to the function which accepts object of type Error.

Is there anything wrong I'm approaching with types in typescript?

NOTE: I'm using this AppException to propagate errors to a global error handler in ExpressJS.

EDIT: This is what I'm trying to do

abstract class AppException extends Error {}
class NotFoundException extends AppException {}

async function getRegisterController(
    req: Request,
    res: Response,
    next: NextFunction,
): Promise<Response | undefined> {
    // business logic
    next(new NotFoundException('User not found');
    return;
 }

 this.server.use(
    (err: Error, req: Request, res: Response, next: NextFunction) => {
        if (err instanceof AppException) {
           // doens't work here
           logger.error(`AppException status code ${err.getStatusCode()}`);
        }
    },
);

These are two middleware functions I'm using in expressjs. In the getRegisterController, I'm calling next() and passing an instance of NotFoundException to the next(). This inturn calls the other middleware and passes the object I sent as error object.

Sriram R
  • 2,109
  • 3
  • 23
  • 40
  • Your question is not about TypeScript. It's about ExpressJS. Use the appropriate tags. – JB Nizet Sep 07 '19 at 06:51
  • Possible duplicate of [Typescript - Extending Error class](https://stackoverflow.com/questions/41102060/typescript-extending-error-class) – lleon Sep 07 '19 at 07:15

2 Answers2

2

The code you provided looks correct with the only exception being you need instanceof (all lowercase):

abstract class AppException extends Error {}

class NotFoundException extends AppException {}

const error = new NotFoundException();

const test = () => {
  if (error instanceof AppException) {
    return "something";
  }
  return "otherThing";
};

console.log(test()) // Print "something" in the console

TypeScript playground

skovy
  • 5,430
  • 2
  • 20
  • 34
  • I do have `instanceof` in my code. I made the typo while typing here. It doesn't work with this too. – Sriram R Sep 07 '19 at 06:16
  • @SriramR this answers shows that the bug is in your code. The code that you haven't posted. You think you're passing an instance of AppException, but you're not. If you did, it would return "something", as this answer proves. – JB Nizet Sep 07 '19 at 06:20
  • One problem with your answer is that my function accepts an error parameter which is of type Error. In your answer, the error object is of type NotFoundException which is what I'm passing, but the function receives the error as an `Error` object. – Sriram R Sep 07 '19 at 06:22
  • @SriramR http://www.typescriptlang.org/play/index.html#code/IYIwzgLgTsDGEAJYBthjAgggB2wUQA9YBTbCASwHsA7BYgiY6gEwzyikqgQG8BfAFACUaDADlKEAGKUAri0IkyVWvUYsMOfEVIUavQcJqQ6HLggC8CasQDuCCdLkKdymgAoAlAG4hsY4iMJlbuxABcCOycUJ6WAHy8AggI5ABmCKEp1JDA1CSU6VqKuiqxPEnJCFDEELJQtABEYJQAtjUAFuTUAOYNvsmCydW19QgNku3EUAAqnT19Any+RtmUyMQAdMiU3e5BEKFmMZ5AA. Again, the problem is in the code you didn't post We can't help you find your mistake if you don't post a complete minimal example reproducing the problem. – JB Nizet Sep 07 '19 at 06:25
  • Oh yes, I understand. Let me post the real example. – Sriram R Sep 07 '19 at 06:35
0

You tsconfig target is proabably ES5. You need to set the prototype manually since typescrtipt>=2.2 or use a newer target.

abstract class AppException extends Error {
  constructor() {
    super();
    Object.setPrototypeOf(this, AppException.prototype);
  }
}

class NotFoundException extends AppException {
  constructor() {
    super();
    Object.setPrototypeOf(this, NotFoundException.prototype);
  }
}

const notFoundException = new NotFoundException();

console.log(notFoundException instanceof AppException);

Check the typescript team explanation for more info

lleon
  • 2,615
  • 1
  • 20
  • 14