前文参考
本文代码基于上一篇文章《NestJS入门8:拦截器》
本文仅对ParseIntPipe管道做简单说明,这个管道的作用是对输入数据转换为所需要的类型(int)
1. 原写法
use.controller.ts中增加一行打印id的类型
postman
打印如下:
2. 管道写法
注:不需要npm 安装任何工具。
Postman Get请求:
http://localhost:3000/user/1
打印如下,管道将string类型的id转换为数字类型
3. 异常验证
对use.controller.ts代码做下小修改,如下:
@Get(':id')
@ApiOperation({summary:'查询用户'})
findOne(@Param('id', new ParseIntPipe()) id){
console.log(typeof id);
return this.userService.findOne(+id);
}
common/filter/http-exception/http-exception.filter.ts 修改为:
postman发送及返回如下:
可见ParseIntPipe内部已做了异常处理,当为非整数时,自动触发了异常输出。