Spring, Java 🌵
Spring 에서의 예외처리 방법 @ControllerAdvice와 @ExceptionHandler
MAYMIN
2024. 6. 1. 12:31
728x90
SMALL
Spring 에서 예외를 처리하는 방법은
@ControllerAdvice와 @ExceptionHandler 를 사용하는 것이다.
예시 코드
Custom Exception 생성
- 각자 서비스의 기능에 맞게 커스텀하여 Exception을 생성
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
서비스에서 예외 발생
- 예외 처리가 필요한 부분에 throw new 를 통해 예외 발생
@Service
public class UserService {
private Map<Long, String> users = new HashMap<>();
public String getUserById(Long id) {
String user = users.get(id);
if (user == null) {
throw new ResourceNotFoundException("User not found with id: " + id);
}
return user;
}
}
발생시킨 예외는
아래의 ExceptionHandler가 에러 처리해줌
ExceptionHandler 생성
- 전역적으로 예외 처리
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception ex) {
return new ResponseEntity<>("Internal server error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@ControllerAdvice
- 역할: 전역 예외 처리 클래스임을 선언
- 사용 위치: 예외 처리 로직을 정의한 클래스에 사용
- 이점: 여러 컨트롤러에서 발생하는 예외를 한 곳에서 처리 가능
@ExceptionHandler
- 역할: 특정 예외를 처리하는 메서드임을 선언
- 사용 위치: @ControllerAdvice 또는 개별 컨트롤러 클래스 내부의 메서드에 사용
- 이점: 특정 예외가 발생했을 때 어떻게 처리할지 정의
728x90
LIST