【发布时间】:2019-09-07 05:57:59
【问题描述】:
假设我有一个像这样的抽象类。
abstract class AppException extends Error {
// constructor, functions, whatever
}
假设我有一个类似的课程
class NotFoundException extends AppException {
}
现在我在随机函数中有一个Error 类型的对象错误。我将NotFoundException 的实例传递给函数。
在错误中,如果我尝试这样做
if (error instanceof AppException) {
return something;
}
return otherThing;
if 语句中的表达式返回 false,当我确定已将 NotFoundException 传递给接受 Error 类型对象的函数时,它返回 otherThing。
打字稿中的类型有什么问题吗?
注意:我正在使用此 AppException 将错误传播到 ExpressJS 中的全局错误处理程序。
编辑: 这就是我正在尝试做的事情
abstract class AppException extends Error {}
class NotFoundException extends AppException {}
async function getRegisterController(
req: Request,
res: Response,
next: NextFunction,
): Promise<Response | undefined> {
// business logic
next(new NotFoundException('User not found');
return;
}
this.server.use(
(err: Error, req: Request, res: Response, next: NextFunction) => {
if (err instanceof AppException) {
// doens't work here
logger.error(`AppException status code ${err.getStatusCode()}`);
}
},
);
这是我在 expressjs 中使用的两个中间件函数。在getRegisterController 中,我正在调用next() 并将NotFoundException 的一个实例传递给next()。这反过来调用其他中间件并将我发送的对象作为错误对象传递。
【问题讨论】:
-
您的问题与 TypeScript 无关。这是关于 ExpressJS 的。使用适当的标签。
标签: typescript express