예외처리를 서비스에서 하는 이유
- 재사용에 유리, 코드가 간결해진다!
- 유지보수에 용이하다.
- 테스트에 용이하다.
예외처리 서비스에 추가하기
TeamNotFoundException 변경하기
- NotFoundException.java 클래스명을 변경하였다.
package com.chan.ssb.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class EntityNotFoundException extends RuntimeException {
public EntityNotFoundException(String message) {
super(message);
}
}
Controller에 예외처리 반환 추가하기
- 기존의 코드에 이미 예외처리 함수를 구현해서 사용중이다
- 다음과 같이 컨트롤러에서 구현할 수 있다.
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<String> handleEntityNotFoundException(EntityNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
- CustomizedResponseEntityExceptionHandler.java와 같이 따로 구현도 가능하다.
TeamService 변경하기
public TeamDTO getTeamById(long id) {
TeamDTO teamDTO = TeamDTO.fromEntity(teamRepository.findById(id).orElse(null));
if(teamDTO == null) {
throw new EntityNotFoundException("Team not found with id: " + id);
}
return teamDTO;
}
public List<TeamDTO> getAllTeams() {
List<Team> teams = teamRepository.findAll();
List<TeamDTO> returnTeams = teams.stream().map(TeamDTO::fromEntity).toList();
if(returnTeams.isEmpty()) {
throw new EntityNotFoundException("No teams found");
}
return returnTeams;
}
TeamController 변경하기
if(teams.isEmpty()) {
throw new EntityNotFoundException("No teams found");
}
Player에도 동일하게 적용하자!
