I've encountered an issue while working with a custom HttpException class in TypeScript. Here's the structure of the class:
class HttpException extends Error {
public status: number | undefined;
public message: string;
public data: any;
constructor(status: number, message: string) {
super(message);
this.status = status;
this.message = message;
this.data = null;
this.name = 'HttpException';
}
}
I throw this exception in a method under a certain condition:
// Inside a method
if (totalBoxCount - labelCount < 0) {
throw new HttpException(StatusCode.ERROR.BAD_REQUEST.code, `Overloaded with labels. We loaded ${labelCount - totalBoxCount} more than expected.`);
}
Now, when I catch this exception in an async method:
private someMethod = async (req: Request, res: Response, next: NextFunction) => {
const data = req.body;
try {
const [result, num] = this.service.anotherMethod(data.text);
} catch (error: any) {
if (error instanceof HttpException) {
next(new HttpException(error.status!, error.message));
} else {
next(new HttpException(StatusCode.ERROR.INTERNAL_SERVER_ERROR.code, StatusCode.ERROR.INTERNAL_SERVER_ERROR.message));
}
}
}
The error instanceof HttpException condition doesn't seem to be working as expected. Even though I throw an HttpException, the code block inside the if statement is not executed.
I've ensured that the HttpException class is correctly defined and inherits from the Error class. Any insights into why the instanceof check might not be working in this context would be greatly appreciated.
Thank you for your assistance!
Extending the built-in Error class is somewhat tricky. Here is some code I have put together some months ago that works for me. I cannot remember how I got this exactly, but I did start from here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types
BTW, there is no need and it's rather potentially a problem to re-declare and re-define (initialize in the constructor) inherited members, e.g.
message.