Skip to content

instanceof CustomError returns false` when throwing shared error classes from another microservice #4

@sharath-wq

Description

@sharath-wq

🐛 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 from CustomError.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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions