TypeScript Express 错误函数

TypeScript Express Error Function

Typescript中错误处理函数的四个参数的类型分别是什么?

app.use((err: ??, req: ??, res: ??, next: ??) => { });

我正在使用 VS Code,但没有提供任何提示。我在所有四个参数下都得到了红色波浪线。

错误显示 "Parameter implicitly has 'any' type"。其实我对这条消息很困惑。如果它将其视为 any 类型,那么这不是一个有效的选择吗?

函数本身具有以下签名(取自DefinitelyTyped):

export type ErrorRequestHandler = (err: any, req: Request, res: Response, next: NextFunction) => any;

因此您可以将函数声明为 ErrorRequestHandler 类型的变量或根据该定义键入参数。

注意:“express-serve-static-core”的类型由“express”的类型导入和重新导出,这是我查找上述定义的地方。

import type { ErrorRequestHandler } from "express";
const errorHandler: ErrorRequestHandler = (err, req, res, next) => {};

app.use(errorHandler);

关于你的第二个与隐式 any 相关的问题,它是导致问题的“隐式”部分,如果你明确键入 any 则不会有任何错误(但也不会有任何打字;请考虑使用

您也可以在编译器配置中禁用 noImplicitAny,但我个人不推荐这样做,因为它可以保护您免受一些 类 错误的影响。

自定义错误类型

使用any完全放弃了Typescript的类型检查优势。因为在 JavaScript 中,可以 throw 任何东西,对于 err 参数,类型 unknown 可以从 Typescript 3.0 开始使用:

app.use((err: unknown, req: Request, res: Response, next: NextFunction) => { })

例子

如果需要,创建自定义错误,如下所示:

// HttpException.ts in exceptions directory of your project.

export class HttpException extends Error {
  public status: number
  public message: string
  constructor(status: number, message: string) {
    super(message)
    this.status = status
    this.message = message
  }
}

然后在任何使用它的地方导入自定义错误:

import { HttpException } from './exceptions/HttpException'

app.use((req: Request, res: Response, next: NextFunction) => {
    const err = new HttpException(404, 'Not Found')
    // Do something with error here...
    next(err)
})

app.use((err: unknown, req: Request, res: Response, next: NextFunction) => {
    if (err instanceof HttpException) {
        // Do something more with the error here...
    }
    next(err)
})

因为err的类型是unknown,我们不能直接访问或修改err。首先,我们需要使用 instanceof 检查类型,结果,智能将 err 转换为该类型(在我们的例子中为 HttpException)。

我们可以根据需要向 HttpException class 添加任何属性和方法,就像我们添加了 statusmessage.


类型定义

如果您还没有完成,您需要为您的 Typescript 项目安装 Node.js 和 Express.js 的类型定义。这将确保识别类型 RequestResponseNextFunction 以及 auto-imported.

为 Node.js 安装类型定义:

npm install --save-dev @types/node

为 Express.js 安装类型定义:

npm install --save-dev @types/express

就是这样!希望对您有所帮助。

我不知道为什么 Typescript 没有得到我们正在传递错误处理程序。

这些是我发现可能的解决方案:

app.use((err, req, res, next) => {}) // KO    

const inVariable : ErrorRequestHandler = (err, req, res, next) => {};

app.use(inVariable); // ok
app.use(((err, req, res, next) => {}) as ErrorRequestHandler); // ok