我不知道这有什么问题,但是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.tsimport AppError from "./AppError";
class BadRequestError extends AppError {
constructor(message?: string) {
super(message || "Client sent a bad request", 400);
}
}
export default BadRequestError;
处理程序try {
throw new BadRequestError();
} catch (err) {
if (err instanceof AppError) {
responseCallback(err.statusCode, err.message, callback);
} else {
responseCallback(500, "Internal Server Error", callback);
}
}
预期结果:实际结果:
最佳答案
解决了!
将此行添加到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