6

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

Community
  • 1
  • 1
Steven
  • 821
  • 1
  • 10
  • 24

1 Answers1

16

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

Steven
  • 821
  • 1
  • 10
  • 24