[NestJS] Try-Catch 예외 처리

혜진·2024년 12월 4일
0

NestJS

목록 보기
12/12
post-thumbnail

NestJS에서 Try-Catch 예외 처리

예외 처리의 중요성

예외 처리는 서버의 안정성을 유지하고, 사용자에게 의미 있는 오류 메시지를 제공하기 위해 필수적이다.

Try-Catch의 역할과 필요성

  • JavaScript와 TypeScript의 기본 예외 처리 방법으로, 특정 코드 블록에서 발생할 수 있는 오류를 처리한다.
  • Try-Catch를 사용하여 비즈니스 로직 내에서 발생한 오류를 제어하거나, 적절한 HTTP 예외를 던질 수 있다.
  • 전역 예외 필터와 함께 사용하여 모듈화된 오류 처리 구조를 만들 수 있다.

📑 NestJS에서의 기본 Try-Catch 사용법

import { Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class ExampleService {
  async performOperation(): Promise<string> {
    try {
      // 오류 발생 가능 코드
      const result = await this.someAsyncTask();
      return result;
    } catch (error) {
      throw new BadRequestException('Operation failed');
    }
  }

  private async someAsyncTask(): Promise<string> {
    throw new Error('Simulated error');
  }
}

📑 NestJS 내장 예외와 Try-Catch

import { NotFoundException } from '@nestjs/common';

@Injectable()
export class UserService {
  getUserById(id: number): any {
    try {
      const user = this.users.find((user) => user.id === id);
      if (!user) throw new NotFoundException('User not found');
      return user;
    } catch (error) {
      throw error;
    }
  }
}

📑 비동기 작업에서의 Try-Catch

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com');
    return response.data;
  } catch (error) {
    throw new Error('Failed to fetch data');
  }
}

📑 전역 예외 필터와 Try-Catch

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

@Catch(HttpException)
export class GlobalExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    response.status(exception.getStatus()).json({ message: exception.message });
  }
}

📑 데이터베이스 오류 처리

async function getUser(id: number) {
  try {
    const user = await this.userRepository.findOneBy({ id });
    if (!user) throw new NotFoundException('User not found');
    return user;
  } catch (error) {
    throw new Error('Database error');
  }
}

0개의 댓글