Nest.js学习之路(10)-Exception in nest.js(下)

如果要完全自订exception,就需要自己撰写class实作ExceptionFilter接口

新增httpexception.filters.ts

import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { HttpException } from '@nestjs/common';

@Catch(HttpException) // 指定Catch HttpException
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) { //预设传入HttpException、及ArgumentHost对象
      const ctx = host.switchToHttp(); // ArgumentsHost是个Wrapper,包含request、response等资讯
    const response = ctx.getResponse(); // 取得request物件,这里指的是Express中request,相关属性可以查阅Express API
    const request = ctx.getRequest(); // 取得response对象
    const status = exception.getStatus();

    response //自定回复格式
      .status(status)
      .json({
        message: '自定错误信息',
        timestamp: new Date().toISOString(),
        requestedFrom: request.hostname,
        status,
      });
  }
}

套用自定Filter,需要用@UseFilters()

@Controller()
@UseFilters(new HttpExceptionFilter())
export class AppController {
@Post()
  @UsePipes(PlatformDTOValidationPipe)
  create(@Body() platformDTO: PlatformDTO){
    throw new HttpException('糟糕!您的要求有问题,请联系管理员', HttpStatus.BAD_REQUEST);
    return `平台:${platformDTO.platformname}已建立`;
  }
}

跑postman测试POST会丟出Exception


Nest.js学习之路(10)-Exception in nest.js(下)_第1张图片
2018110603.png

可以看到自定错误信息

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

tuiguang.png

你可能感兴趣的:(Nest.js学习之路(10)-Exception in nest.js(下))