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.