gpt4 book ai didi

node.js - "Instanceof"工作不正常

转载 作者:搜寻专家 更新时间:2023-11-01 00:28:39 25 4
gpt4 key购买 nike

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

处理程序.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 类。

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

关于node.js - "Instanceof"工作不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47429157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com