내일배움캠프

[내일배움캠프] 예외 처리

munsik22 2026. 4. 10. 16:11

🧩 API 예외 처리란?

웹 애플리케이션의 에러

  • HTTP 상태 코드의 종류
    • 2xx Success: 성공
    • 4xx Client Error: 클라이언트 에러 (잘못된 요청)
    • 5xx Server Error: 서버 에러

Spring의 예외 처리 방법

  • RestApiException 생성
@Getter
@AllArgsConstructor
public class RestApiException {
    private String errorMessage;
    private int statusCode;
}
  • FolderController: 예외 처리 핸들러(@ExceptionHandler) 추가
@ExceptionHandler({IllegalArgumentException.class})
public ResponseEntity<RestApiException> handleException(IllegalArgumentException ex) {
    RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
    return new ResponseEntity<>(
            // HTTP body
            restApiException,
            // HTTP status code
            HttpStatus.BAD_REQUEST
    );
}

Global 예외 처리

컨트롤러마다 예외 처리를 해 주는 것이 아니라 Global하게 처리를 할 수도 있다.

  • FolderController: 예외 처리 핸들러(@ExceptionHandler) 삭제
  • GlobalExceptionHandler 생성
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({IllegalArgumentException.class})
    public ResponseEntity<RestApiException> handleException(IllegalArgumentException ex) {
        RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
        return new ResponseEntity<>(
                // HTTP body
                restApiException,
                // HTTP status code
                HttpStatus.BAD_REQUEST
        );
    }
}

에러 메시지 관리하기

  • /resources/messages.properties 생성
below.min.my.price=최저 희망가는 최소 {0}원 이상으로 설정해 주세요.
not.found.product=해당 상품이 존재하지 않습니다.
  • Spring Boot에서는 messageSource가 자동으로 Bean으로 등록된다.
  • 사용 예시
if (myprice < MIN_MY_PRICE) {
    throw new IllegalArgumentException(messageSource.getMessage(
            "below.min.my.price",
            new Integer[]{MIN_MY_PRICE},
            "Wrong Price",
            Locale.getDefault()
    ));
}