0
0

NestJSで良い感じに例外を捌いていく

Posted at

概要

NestJSで例外処理を実装する際に個人的に良い感じに実装して、フロント側にエラーレスポンスを返す備忘録。

手順

  1. 例外レスポンス用のInterfaceを用意する。

    src/common/exceptions/exception.interface.ts
    export interface Exception {
      statusCode: number
      message: string
      timestamp: Date
      path: string
    }
    
  2. グローバルで使えるExceptionFilterを実装する。

    src/common/exceptions/exception.filter.ts
    import {
      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
          });
      }
    }
    
  3. ExceptionFilterをグローバルに適用されるようにする。

    src/main.ts
    import { 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】例外処理を共通化する方法

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0