개발/Spring

@ControllerAdvice와 @ExceptionHandler를 사용한 글로벌 예외 처리

피터JK 2025. 2. 17. 17:21
728x90

Spring Boot에서 글로벌 예외 처리를 구현

1. @ControllerAdvice와 @ExceptionHandler를 사용한 글로벌 예외 처리

📌 구현 예제

package com.example.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

// 글로벌 예외 처리를 위한 클래스
@ControllerAdvice
public class GlobalExceptionHandler {

    // 예제: 특정 예외(CustomException) 처리
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<String> handleCustomException(CustomException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
    }

    // 예제: NullPointerException 처리
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<String> handleNullPointerException(NullPointerException ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Null 값이 존재합니다.");
    }

    // 예제: 모든 예외 처리 (최상위 예외)
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<String> handleGlobalException(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("서버 내부 오류가 발생했습니다.");
    }
}

2. Custom Exception 클래스 생성

package com.example.exception;

// 사용자 정의 예외 클래스
public class CustomException extends RuntimeException {
    public CustomException(String message) {
        super(message);
    }
}

3. 테스트용 컨트롤러 생성

package com.example.controller;

import com.example.exception.CustomException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/test/custom-exception")
    public String throwCustomException() {
        throw new CustomException("사용자 정의 예외 발생!");
    }

    @GetMapping("/test/null-pointer")
    public String throwNullPointerException() {
        throw new NullPointerException();
    }

    @GetMapping("/test/global-exception")
    public String throwGlobalException() {
        throw new RuntimeException("일반 예외 발생!");
    }
}

4. 테스트 요청 및 응답 예시

✅ GET /test/custom-exception

  • 응답 코드: 400 Bad Request
  • 응답 본문:
    "사용자 정의 예외 발생!"
    

✅ GET /test/null-pointer

  • 응답 코드: 500 Internal Server Error
  • 응답 본문:
    "Null 값이 존재합니다."
    

✅ GET /test/global-exception

  • 응답 코드: 500 Internal Server Error
  • 응답 본문:
    "서버 내부 오류가 발생했습니다."
    

5. 설명

  • @ControllerAdvice를 사용하여 모든 컨트롤러에서 발생하는 예외를 글로벌하게 처리.
  • @ExceptionHandler를 활용하여 특정 예외를 핸들링.
  • @ResponseStatus를 사용하여 HTTP 상태 코드 설정.
  • ResponseEntity를 반환하여 클라이언트에게 적절한 응답을 제공.

이제 Spring Boot 프로젝트에서 예외 처리를 효과적으로 적용할 수 있습니다. 

728x90