iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 10
0
Modern Web

讀官網文件邊走邊學nest.js系列 第 10

Day10-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,
      });
  }
}

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


@Controller()
@UseFilters(new HttpExceptionFilter())
export class AppController {
@Post()
  @UsePipes(UserDTOValidationPipe)
  create(@Body() userDTO: UserDTO){
    throw new HttpException('糟糕!您的要求有問題,請洽系統管理員', HttpStatus.BAD_REQUEST);
    return `使用者:${userDTO.username}已建立`;
  }
}

跑postman測試POST會丟出Exception

可以看到自訂錯誤訊息


上一篇
Day9-Exceptions in nest.js(上)
下一篇
Day11-Guard(Authentication) in nest.js(上)
系列文
讀官網文件邊走邊學nest.js31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言