[Start Spring Boot] 예외처리 서비스로 옮기기

·2024년 3월 27일
0

Start Spring Boot!

목록 보기
30/53
post-thumbnail

예외처리를 서비스에서 하는 이유

  • 재사용에 유리, 코드가 간결해진다!
  • 유지보수에 용이하다.
  • 테스트에 용이하다.

예외처리 서비스에 추가하기

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 변경하기

  • TeamService.java
    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에도 동일하게 적용하자!

profile
백엔드 개발자가 꿈인 컴공과

0개의 댓글

관련 채용 정보