"Instanceof" 工作不正常

"Instanceof" not working properly

我不知道这有什么问题,但是 instanceof 似乎不起作用。

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);
    }
}

预期结果:

Status Code: 400

Message: Client sent a bad request

实际结果:

Status Code: 500

Message: Internal Server Error

已解决!

将此行添加到 BadRequestError class。

Object.setPrototypeOf(this, BadRequestError.prototype);

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;

参考: