역할
- Spring Boot REST API 전역 예외 처리 담당
ApiException, Spring Validation, 그 외 모든 예외를 일관된 JSON 응답으로 변환
1. 핵심 구조
@RestControllerAdvice
public class GlobalExceptionHandler {
// 커스텀 ApiException 처리
@ExceptionHandler(ApiException.class)
public ResponseEntity<ApiError> handleApi(ApiException e) {
ErrorCode errorCode = e.getErrorCode();
return ResponseEntity
.status(errorCode.getStatus())
.body(ApiError.of(
errorCode.name(),
e.getMessageToSend()
));
}
// Spring Validation 예외 처리
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleValidation(MethodArgumentNotValidException e) {
return ResponseEntity
.status(ErrorCode.VALIDATION_ERROR.getStatus())
.body(ApiError.of(
ErrorCode.VALIDATION_ERROR.name(),
ErrorCode.VALIDATION_ERROR.getDefaultMessage()
));
}
// 처리되지 않은 모든 예외
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiError> handleEtc(Exception e) {
// TODO: 내부 로깅 필수
return ResponseEntity
.status(ErrorCode.INTERNAL_ERROR.getStatus())
.body(ApiError.of(
ErrorCode.INTERNAL_ERROR.name(),
ErrorCode.INTERNAL_ERROR.getDefaultMessage()
));
}
}
2. 설명
@RestControllerAdvice → 모든 REST 컨트롤러에서 발생한 예외를 글로벌로 처리
@ExceptionHandler → 예외 타입별 처리 분기
ApiException → 커스텀 메시지 + ErrorCode 기반 응답
MethodArgumentNotValidException → 입력값 검증 실패 시 400 응답
Exception → 예측하지 못한 서버 오류 → 500 응답
- 모든 응답은
ApiError DTO로 JSON 표준화
3. 포인트
- 중앙 집중식 예외 처리 → 컨트롤러에서 try-catch 불필요
- ErrorCode 연계 → HTTP 상태 코드 + 내부 코드 + 메시지 통합 관리
- 입력값 검증과 서버 오류를 분리하여 프론트에서 처리 용이
- 필요 시 로깅/모니터링/알림 기능 추가 가능
4. API 예외 처리 흐름도
[클라이언트 요청]
│
▼
[Controller / Service 로직 수행]
│
├─ 정상 처리 → Response 반환
│
└─ 오류 발생 →
├─ throw new ApiException(ErrorCode, [커스텀 메시지])
│ │
│ ▼
│ ApiException 객체 생성
│ │
│ ▼
│ getErrorCode() → ErrorCode 확인
│
├─ 입력값 검증 실패 → MethodArgumentNotValidException
│
└─ 그 외 예외 → Exception
│
▼
[GlobalExceptionHandler]에서 catch
│
▼
ResponseEntity<ApiError> 생성 (HTTP 상태 + 메시지)
│
▼
[클라이언트 JSON 응답]