-
Notifications
You must be signed in to change notification settings - Fork 89
Open
Description
🐛 Issue: instanceof CustomError
returns false
when throwing shared error classes from another microservice
When throwing an error like this in a route:
throw new NotAuthorizedError('test', 'auth-service');
Then trying to check its type:
if (err instanceof CustomError) {
// This never runs
}
I get:
Instance of CustomError? false
Constructor: Error
Has serializeErrors: undefined
Is prototype equal: false
💡 Root Cause
This is a JavaScript quirk when extending Error
in TypeScript — especially when transpiled. The Error
class doesn't play nicely with inheritance, and the prototype chain is broken after extending it.
Even though everything looks correct, the instanceof
check fails because:
this
inside your custom error does not inherit fromCustomError.prototype
.- This also breaks access to methods like
serializeErrors()
.
✅ Fix
Update the constructor in the shared CustomError
class like so:
export abstract class CustomError extends Error {
abstract statusCode: number;
abstract status: string;
comingFrom: string;
constructor(message: string, comingFrom: string) {
super(message);
// ✅ FIX: Restore prototype chain
Object.setPrototypeOf(this, new.target.prototype);
// ✅ Optional: cleaner stack trace
Error.captureStackTrace(this, this.constructor);
this.comingFrom = comingFrom;
}
serializeErrors(): IError {
return {
message: this.message,
statusCode: this.statusCode,
status: this.status,
comingFrom: this.comingFrom,
};
}
}
Result:
After applying this fix, instanceof
works as expected:
err instanceof CustomError // ✅ true
typeof err.serializeErrors // ✅ 'function'
err.constructor.name // ✅ 'NotAuthorizedError'
Metadata
Metadata
Assignees
Labels
No labels