美文网首页让前端飞Web前端之路前端开发
Nest.js学习之路(9)-Exceptions in nes

Nest.js学习之路(9)-Exceptions in nes

作者: cbw100 | 来源:发表于2019-06-10 17:28 被阅读3次

nest.js处理例外使用HttpException这个base class

例如:
app.controller.ts

...
 @Post()
  @UsePipes(PlatfofrmDTOValidationPipe)
  create(@Body() platformDTO: PlatformDTO){
    //丟出badreqest例外
   throw new HttpException('糟糕!您的要求有问题,请联系系统管路员', HttpStatus.BAD_REQUEST);
    
    return `平台:${platformDTO.platformname}已建立`;
  }
... 

使用postman测试


2018110601.png

nest.js已經內建好常用的exception如:

  • BadRequestException
  • UnauthorizedException
  • NotFoundException
  • ForbiddenException

如:
app.controller.ts

...
  @Get('users')
  queryedList(@Query() query){
    throw new UnauthorizedException('请登入');
    return query;
  }
...
2018110602.png

除了内建的exception,也可以自订exception,在nest.js里称exception filters

这部分下一章在继续。

推荐一下我的公众号: 【 geekjc 】,微信号: 【 c8706288 】一起学习交流编程知识,分享经验,各种有趣的事。

tuiguang.png

相关文章

网友评论

    本文标题:Nest.js学习之路(9)-Exceptions in nes

    本文链接:https://www.haomeiwen.com/subject/ampyxqtx.html