I've created a custom exception error class, BookingError
, that is supposed to handle all booking-related errors that are thrown:
class BookingError extends Error{
constructor(message: string){
super(message);
this.name = "BookingError";
}
}
When using this to throw exceptions, I've run into an issue where I cannot reliably check the instanceof
against the class to decide what to do with the error.
const throwError = () => {
throw new BookingError("This is a test.");
};
const testErrorException = () => {
try{
throwError();
} catch(err: unknown){
// This will always result in a false output.
console.log(err instanceof BookingError);
}
};
This code will result in the following:
Error [BookingError]: This is a test.
EDIT: Interestingly enough, albeit hacky, the following code will result in the expected output:
if((err as BookingError).name === "BookingError"){
// This will output "This is a test."
console.log((err as BookingError).message);
}