Notice
Recent Posts
Recent Comments
Link
«   2026/01   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

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;
}