Spring/강의

[📘 심화 Spring] 3-2. API 예외 처리

가지코딩 2025. 6. 9. 20:56

📘 목차

  1. @ExceptionHandler
  2. @ControllerAdvice
  3. @RestControllerAdvice
  4. 정리

1. @ExceptionHandler

  • 특정 컨트롤러 또는 컨트롤러 메서드 내에서 발생하는 예외를 처리하기 위해 사용한다.
  • 메서드에 붙이며, 처리할 예외 타입을 지정한다.
  • 특징
    • 해당 컨트롤러 내에서만 적용됨
    • 여러 예외를 하나의 메서드로 처리 가능 (파라미터에 여러 예외 타입 지정)
@RestController
public class UserController {

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
        // 예외 발생 가능
        return userService.findById(id);
    }

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<String> handleUserNotFound(UserNotFoundException e) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
    }
}

2. @ControllerAdvice

  • 전역 예외 처리용 클래스에 사용
  • 모든 컨트롤러(@Controller)에서 발생하는 예외를 공통적으로 처리할 수 있다.
  • 특징
    • Spring MVC의 모든 @Controller 대상
    • @ResponseBody가 없기 때문에 기본적으로 HTML을 반환한다 (View 기반 응답)
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException e) {
        return ResponseEntity.badRequest().body("잘못된 요청: " + e.getMessage());
    }
}

3. @RestControllerAdvice

  • @ControllerAdvice + @ResponseBody
  • API 프로젝트에서 주로 사용
  • JSON 형태의 응답을 반환
  • 특징
    • 모든 @RestController 또는 @Controller + @ResponseBody 대상
    • JSON 기반 API 응답을 처리하기에 적합
@RestControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(CustomApiException.class)
    public ResponseEntity<ApiErrorResponse> handleCustomApiException(CustomApiException e) {
        ApiErrorResponse response = new ApiErrorResponse(e.getCode(), e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }
}

4. 정리

항목 @ExceptionHandler @ControllerAdvice @RestControllerAdvice
적용 대상 특정 컨트롤러 전체 컨트롤러(@Controller) 전체 REST 컨트롤러(@RestController)
위치 컨트롤러 클래스 내부 전역 예외 처리 클래스 전역 예외 처리 클래스
응답 형식 자유 (HTML/JSON 등) HTML(View 반환) JSON(API 응답)
주 용도 개별 컨트롤러 예외 처리 전역 HTML 예외 처리 전역 API 예외 처리