역할


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. 설명


3. 포인트


4. API 예외 처리 흐름도

[클라이언트 요청]
       │
       ▼
[Controller / Service 로직 수행]
       │
       ├─ 정상 처리 → Response 반환
       │
       └─ 오류 발생 →
               ├─ throw new ApiException(ErrorCode, [커스텀 메시지])
               │        │
               │        ▼
               │   ApiException 객체 생성
               │        │
               │        ▼
               │   getErrorCode() → ErrorCode 확인
               │
               ├─ 입력값 검증 실패 → MethodArgumentNotValidException
               │
               └─ 그 외 예외 → Exception
                       │
                       ▼
              [GlobalExceptionHandler]에서 catch
                       │
                       ▼
         ResponseEntity<ApiError> 생성 (HTTP 상태 + 메시지)
                       │
                       ▼
                 [클라이언트 JSON 응답]