“Instanceof”无法正常工作

时间:2017-11-22 07:37:41

标签: node.js custom-exceptions

我不知道这有什么问题,但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);
    }
}

预期结果:

  

状态代码:400

     

消息:客户端发送了错误的请求

实际结果:

  

状态代码:500

     

消息:内部服务器错误

1 个答案:

答案 0 :(得分:1)

解决!

将此行添加到BadRequestError类。

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;

参考: https://stackoverflow.com/a/41429145/8504830