我不知道这有什么问题,但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
消息:内部服务器错误
答案 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;