自定义错误类型
使用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 类添加任何属性和方法,就像我们添加了status 和message 一样。
类型定义
如果您还没有完成,您需要为您的 Typescript 项目安装 Node.js 和 Express.js 的类型定义。这将确保类型 Request、Response 和 NextFunction 将被识别并自动导入。
为 Node.js 安装类型定义:
npm install --save-dev @types/node
为 Express.js 安装类型定义:
npm install --save-dev @types/express
就是这样!希望对您有所帮助。