error-handling
內建 Http Exception
Nest 有內建一套基於 HttpException
的 Exception 可以使用,讓開發者根據不同的錯誤來選用不同的 Exception,這裡將它們列出來給大家參考:
BadRequestException
UnauthorizedException
NotFoundException
ForbiddenException
NotAcceptableException
RequestTimeoutException
ConflictException
GoneException
HttpVersionNotSupportedException
PayloadTooLargeException
UnsupportedMediaTypeException
UnprocessableEntityException
InternalServerErrorException
NotImplementedException
ImATeapotException
MethodNotAllowedException
BadGatewayException
ServiceUnavailableException
GatewayTimeoutException
PreconditionFailedException
自訂 Exception
前面有提到 HttpException
為標準的 class
,這表示我們可以自行設計類別來繼承 HttpException
,達到自訂 Exception 的效果。不過大多數情況下不太需要自訂,因為 Nest 提供的 Exception 已經很夠用了!這邊我們先新增一個 custom.exception.ts
在 src/exceptions
底下:
import { HttpException, HttpStatus } from '@nestjs/common';
export class CustomException extends HttpException {
constructor () {
super('未知的錯誤', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
修改 app.controller.ts
進行測試:
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { CustomException } from './exceptions/custom.exception';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {
}
@Get()
getHello(): string {
throw new CustomException();
return this.appService.getHello();
}
}
全域 Exception filter
如果我的 Exception filter 是要套用到每一個資源上的話,不就要替每個 Controller 都添加 @UseFilters
嗎?別擔心,Nest 非常貼心提供了配置在全域的方法,只需要在 main.ts
進行修改即可:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './filters/http-exception.filter';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(3000);
}
bootstrap();
透過 useGlobalFilters
來指定全域的 Exception filter,實在是非常方便!
[NestJS 帶你飛!] DAY08 - Exception & Exception filters - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天