Springboot GlobalException
🧩 Global Exception 처리란
정의
Spring Boot의 Global Exception 처리는 컨트롤러나 서비스에서 발생한 예외를 한 곳에서 모아서 처리하는 방식이다. 예외 응답을 일관되게 만들고, 컨트롤러마다
try-catch를 반복하지 않게 해준다.
- 예외 응답 형식을 통일할 수 있다.
- 컨트롤러 코드가 간결해진다.
- 로깅과 에러 메시지 관리를 한 곳에서 할 수 있다.
⚙️ 전역 예외 처리 방법
@ControllerAdvice
- 전역 예외 처리 클래스를 선언할 때 사용한다.
- 뷰 응답과 API 응답 둘 다 다룰 수 있다.
@RestControllerAdvice
@ControllerAdvice와@ResponseBody를 함께 쓰는 형태다.- JSON API를 반환하는 경우 더 자주 사용한다.
🛠 기본 예제
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = { IllegalArgumentException.class })
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
return new ResponseEntity<>("Invalid input: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(value = { NullPointerException.class })
public ResponseEntity<String> handleNullPointerException(NullPointerException ex) {
return new ResponseEntity<>("Unexpected error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(value = { Exception.class })
public ResponseEntity<String> handleGeneralException(Exception ex) {
return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
🧩 자주 쓰는 예외 처리 방식
@ExceptionHandler
- 특정 예외 타입별로 처리 메서드를 분리한다.
- 예외 종류에 따라 상태 코드와 응답 메시지를 다르게 줄 수 있다.
ResponseEntity
- 응답 본문과 HTTP 상태 코드를 함께 제어할 수 있다.
- API 응답에서 가장 많이 사용된다.
ResponseEntityExceptionHandler
- Spring이 제공하는 기본 예외 처리 클래스를 확장할 수 있다.
MethodArgumentNotValidException같은 검증 예외를 다루기 좋다.
🛠 예외 응답 예시
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("서버 처리 중 오류가 발생했습니다.");
}
}
⚠️ 주의사항
- 너무 많은 예외를 하나의 핸들러에 몰아넣으면 유지보수가 어려워질 수 있다.
- 예외별로 HTTP 상태 코드와 메시지 전략을 나누는 것이 좋다.
Exception.class를 마지막에 두어야 구체적인 예외 핸들러가 먼저 동작한다.- 검증 오류와 비즈니스 오류는 분리해서 다루는 편이 좋다.
✅ 장점과 단점
✅ 장점
- 컨트롤러마다
try-catch를 작성할 필요 없이 예외를 중앙에서 처리 가능 - 예외 메시지를 일관되게 관리할 수 있어 유지보수성 향상
- API 응답 형식을 통일하기 쉬움
❌ 단점
- 전역 예외 처리만으로 해결되지 않는 경우가 있어, 특정 예외는 개별 처리 필요
- 예외 처리 로직이 복잡해질 경우 관리가 어려울 수 있음
📌 정리
- Global Exception 처리는 예외를 한 곳에서 모아 다루는 방식이다.
- API 응답은 보통
@RestControllerAdvice와@ExceptionHandler조합을 많이 쓴다. - 상태 코드와 응답 메시지를 일관되게 관리할 수 있다.
댓글남기기