⚡
@ExceptionHandler
- 컨트롤러 클래스 내에서 특정 예외를 처리하는 메서드를 정의하는 어노테이션
예외가 발생했을 때 설정된 메서드가 호출되어 예외를 처리함

@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Map<String, String>> handleIllegalArgumentException(IllegalArgumentException ex) {
Map<String, String> response = new HashMap<>();
response.put("error", ex.getMessage());
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(response);
}
🛠️ 특징
throw new로 예외 발생 → 지정된 메서드가 실행됨📊 실행 예시
IllegalArgumentException → 등록된 @ExceptionHandler 실행 ✅
NullPointerException → 처리자 없음 → 500 Internal Server Error ❌
Service Layer Exception → 같은 컨트롤러의 핸들러 실행됨
핸들러 없는 컨트롤러 → 예외 전파됨 (500)
⚠️ 문제점
📢
@ControllerAdvice
@RestController를 포함하고 있어 반환 값이 자동으로 JSON 형태로 변환되며
REST API에서 발생하는 예외를 처리할 때 사용함

🌍
@ControllerAdvice&@RestControllerAdvice
✨ 차이점
@ControllerAdvice → 전역 예외 처리, 주로 뷰(View) 반환@RestControllerAdvice → 전역 예외 처리 + JSON 반환 (REST API용)@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Map<String, String>> handleIllegalArgumentException(IllegalArgumentException ex) {
Map<String, String> response = new HashMap<>();
response.put("error", ex.getMessage());
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(response);
}
}
🛠️ 특징
@RestControllerAdvice 권장 → 자동으로 JSON 응답📂 Annotation 비교 정리
| Annotation | 적용 범위 | 반환 형식 | 특징 |
|---|---|---|---|
@ExceptionHandler | 단일 컨트롤러 내부 | 뷰 이름, 문자열, ResponseEntity | 특정 컨트롤러 전용 |
@ControllerAdvice | 애플리케이션 전역 | 뷰 이름, 문자열 | 모든 컨트롤러 전역 적용 |
@RestControllerAdvice | 애플리케이션 전역 | JSON (ResponseEntity) | REST API 전역 적용, JSON 자동 변환 |
🧠 요약 정리
| Annotation | 적용 범위 | 반환 형식 | 장점 | 단점 |
|---|---|---|---|---|
@ExceptionHandler | 단일 컨트롤러 내부 | 뷰 이름, 문자열, ResponseEntity | - 특정 컨트롤러 예외를 세밀하게 처리 가능 - 계층별로 throw 만 하면 됨 | - 컨트롤러마다 중복 코드 발생 - 단일 책임 원칙 위반 |
@ControllerAdvice | 애플리케이션 전역 | 뷰 이름, 문자열 | - 모든 컨트롤러에 전역 적용 - 예외 처리 코드 재사용 가능 | - REST API에서는 직접 JSON 변환 필요 |
@RestControllerAdvice | 애플리케이션 전역 | JSON (ResponseEntity) | - REST API 전역 예외 처리 - JSON 자동 변환 - 유지보수성과 재사용성 ↑ | - 외부 라이브러리 예외 처리 시 변환 로직 필요 |
👉 정리:
@ExceptionHandler@ControllerAdvice@RestControllerAdvice