🧩 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()
));
}
'내일배움캠프' 카테고리의 다른 글
| [내일배움캠프] 서비스 디스커버리, 로드 밸런싱, 서킷 브레이커, API 게이트웨이 (0) | 2026.04.13 |
|---|---|
| [내일배움캠프] MSA와 Spring Cloud (0) | 2026.04.11 |
| [내일배움캠프] Spring AOP (0) | 2026.04.10 |
| [내일배움캠프] 단위 테스트와 통합 테스트 (0) | 2026.04.10 |
| [내일배움캠프] 카카오 소셜 로그인 구현 (0) | 2026.04.10 |