概要
NestJSで例外処理を実装する際に個人的に良い感じに実装して、フロント側にエラーレスポンスを返す備忘録。
手順
-
例外レスポンス用のInterfaceを用意する。
src/common/exceptions/exception.interface.tsexport interface Exception { statusCode: number message: string timestamp: Date path: string }
-
グローバルで使えるExceptionFilterを実装する。
src/common/exceptions/exception.filter.tsimport { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, } from '@nestjs/common'; import { Exception } from './exception.interface'; @Catch() export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost): Exception { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const request = ctx.getRequest(); const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR; const message = exception instanceof HttpException ? exception.getResponse() : 'Internal server error' response .status(status) .json({ statusCode: statusCode, message: message, timestamp: new Date().toISOString(), path: request.url }); } }
-
ExceptionFilterをグローバルに適用されるようにする。
src/main.tsimport { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { HttpExceptionFilter } from '../../exceptions/exception.filter'; async function bootstrap() { const app = await NestFactory.create(AppModule); // グローバルフィルターとしてHttpExceptionFilterを適用 app.useGlobalFilters(new HttpExceptionFilter()); await app.listen(3000); } bootstrap();
参考
overview-exceptionfilters
NestJS の Exception Filter を使って例外ベースで異常系の処理を行う
NestJSのExceptionFiltersでいい感じに例外処理とログ出力を実現する方法
【NestJS】例外処理を共通化する方法