본문 바로가기

프레임워크(Framework)/Spring

그래서 예외 처리를 어디서 해야 할까?

예외 처리를 어디서 하는 지에 대한 결정은 요구 사항에 따라 다르다고 생각한다. 

 

1. Service 계층에서 예외 처리

2. Controller 계층에서 예외 처리

3. 전역(Global) 예외 처리

 

이전에 배운 것에 따르면 Service 계층에서는 비즈니스 로직을 포함하며, 데이터 연산을 수행한다.

만약 비즈니스 로직에 가까운 예외는 Service 계층에서 처리하는 것이 적절하다. 

@Service
public class UserService {

    public User getUserById(int id) {
        Optional<User> user = userRepository.findById(id);
        return user.orElseThrow(() -> new UserNotFoundException("사용자 없음"));
    }
}
public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(String message) {
        super(message);
    }
}

 

Controller 계층은 클라이언트와 상호작용하는 계층이다. 만약 클라이언트에게 적절한 HTTP 응답 코드를 반환하는 것이 목적이라면 컨트롤러 계층에서 처리한다.

 

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users/{id}")
    public ResponseEntity<User> getUser(@PathVariable int id) {
        try {
            User user = userService.getUserById(id);
            return new ResponseEntity<>(user, HttpStatus.OK);
        } catch (UserNotFoundException e) {
            return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
        }
    }
}

 

 

전역 예외 처리를 사용하면 애플리케이션 전반에 걸쳐 발생하는 예외를 한 곳에서 처리할 수 있어 일관된 예외 처리를 가능하게 한다. 사실 이 부분은 아직 예시를 구현하기에 능력이 부족이라 추후에 업데이트 해볼 예정이다.