Search code examples
node.jscustom-exceptions

"Instanceof" not working properly


I don't know what wrong with this, but instanceof doesn't seem to work.

AppError.ts

class AppError extends Error {
    public statusCode;

    constructor(message, statusCode) {
      super(message);

      this.name = this.constructor.name;

      Error.captureStackTrace(this, this.constructor);

      this.statusCode = statusCode || 500;
    }
}

export default AppError;

BadRequestError.ts

import AppError from "./AppError";

class BadRequestError extends AppError {
    constructor(message?: string) {
        super(message || "Client sent a bad request", 400);
    }
}

export default BadRequestError;

handler.ts

try {
    throw new BadRequestError();
} catch (err) {
    if (err instanceof AppError) {
        responseCallback(err.statusCode, err.message, callback);
    } else {
        responseCallback(500, "Internal Server Error", callback);
    }
}

Expected Result:

Status Code: 400

Message: Client sent a bad request

Actual Result:

Status Code: 500

Message: Internal Server Error


Solution

  • Solved!

    Added this line to BadRequestError class.

    Object.setPrototypeOf(this, BadRequestError.prototype);
    

    New BadRequestError:

    import AppError from "./AppError";
    
    class BadRequestError extends AppError {
        constructor(message?: string) {
            super(message || "Client sent a bad request", 400);
    
            Object.setPrototypeOf(this, BadRequestError.prototype);
        }
    }
    
    export default BadRequestError;
    

    Reference: https://stackoverflow.com/a/41429145/8504830