관리 메뉴

Mini

[Nest JS] 없는 게시물 찾을때 예외처리 본문

JS/Nest.js

[Nest JS] 없는 게시물 찾을때 예외처리

Mini_96 2024. 8. 17. 20:55

* 문제 : ewe라는 게시물을 찾으면 빈칸이 나온다.

//localhost:3030/boards/1234(id) 가져오는 방법 = @param
@Get('/:id')
getBoardByID(@Param('id') id:string) : Board{
  return this.boardsService.getBoardByID(id);
}

 

* fix

getBoardByID(id:string): Board{
  const found = this.boards.find((board) => board.id===id);
  if(!found){
    throw new NotFoundException();
  }
  return found;
}

 

* 원하는 msg 넣기

getBoardByID(id:string): Board{
  const found = this.boards.find((board) => board.id===id);
  if(!found){
    throw new NotFoundException(`Can\`t find board with id ${id}`);
  }
  return found;
}