[TIL] Nest.js에서의 예외처리/ 알고리즘

Cherry Jin·2024년 1월 4일
0

sparta_내배캠

목록 보기
37/53
post-thumbnail

강의만 따라가다보니 예외처리중에 아는 것은 BadRequestExceotion 하나뿐이었다.

보너스로 강의자료에서만 다루고 있는 Nest.js에서의 예외처리를 정리해보자.

공식문서에서의 예외처리

cats.controller.ts

@Get()
async findAll() {
  throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
}

//호출시 결과
{
  "statusCode": 403,
  "message": "Forbidden"
}

위는 공식문서에서 제공하는 표준 예외처리 방식이다. 또는 다음과 같이 사용한다.

cats.controller.ts

@Get()
async findAll() {
  try {
    await this.service.findAll()
  } catch (error) { 
    throw new HttpException({
      status: HttpStatus.FORBIDDEN,
      error: 'This is a custom message',
    }, HttpStatus.FORBIDDEN, {
      cause: error
    });
  }
}


//호출시 결과
{
  "status": 403,
  "error": "This is a custom message"
}

아래는 공식적으로 제공하는 표준 예외 세트

BadRequestException
UnauthorizedException
NotFoundException
ForbiddenException
NotAcceptableException
RequestTimeoutException
ConflictException
GoneException
HttpVersionNotSupportedException
PayloadTooLargeException
UnsupportedMediaTypeException
UnprocessableEntityException
InternalServerErrorException
NotImplementedException
ImATeapotException
MethodNotAllowedException
BadGatewayException
ServiceUnavailableException
GatewayTimeoutException
PreconditionFailedException

이 오류들은 다음과 같이 사용된다.

//보통 전달하는 방법은 아래와 같다.
throw new BadRequestException('Something bad happened')
//혹은 아래와 같이 오류와 설명을 모두 전달할 수 있다.
throw new BadRequestException('Something bad happened', { cause: new Error(), description: 'Some error description' })

//응답
{
  "message": "Something bad happened",
  "error": "Some error description",
  "statusCode": 400,
}

알고리즘 스터디

2018 KAKAO BLIND RECRUITMENT 알고리즘 스터디 시간에 같이 푼 문제

/**
 * 1. n은 배열 길이이자, 이진수의 자릿수
 * 2. arr의 각 수를 이진수로 변환 - 완
 * 3. 이진수 상태에서 1/0 자리 확인하기 - string 상태에서?
 *  - 다 풀어해치고 비교후에 n기준으로 다시 합치는 방법
 * 4. 1을 #으로 0은 공백으로 변환하기
 */

function solution(n, arr1, arr2) {
  let result = [];
  /**배열 받아서 이진법의 새로운 배열로 만들기 */
  const newArr1 = arr1.map((e) => e.toString(2).padStart(n, '0'));
  const newArr2 = arr2.map((e) => e.toString(2).padStart(n, '0'));
  /**배열 내부 요소 확인하고 변경하기 */
  for (let i = 0; i < n + 1; i++) {
    if (newArr1[i] === newArr2[i]) {
      result.push(newArr1[i]);
    } else {
    }
  }
  return result;
}

let n = 5;
let arr1 = [9, 20, 28, 18, 11];
let arr2 = [30, 1, 21, 17, 28];

console.log(solution(n, arr1, arr2));

풀이 시간을 40분 정도로 잡았더니 여기까지 하고 다 되어버렸다. 개인공부할 것

profile
풀스택이 되버린 주니어 개발자

0개의 댓글