Spring
Error 메시지 관리하기 + global 에 적용예시.
sehunbang
2024. 2. 19. 18:12
Spring의 properties 파일을 이용한 에러 메시지 관리
- properties 파일을 이용하여 에러 메시지를 관리할 수 있습니다.
- 에러 메시지는 properties 파일에서 key-value 형태로 작성되며, 작성된 값은 messageSource 를 Bean으로 등록하여 사용할 수 있습니다.
resources > messages.properties (새파일)

필요 한데
private final MessageSource messageSource;
추가
(자동으로 bean 으로 등록 됩니다)
사용 예시
throw new IllegalArgumentException(
messageSource.getMessage(
"below.min.my.price",
new Integer[]{min_price},
"Wrong Price",
Locale.getDefault() //
)
);
messageSource.getMessage()메서드
- 첫번째 파라미터는 messages.properties 파일에서 가져올 메시지의 키 값을 전달합니다.
- 두번째 파라미터는 메시지 내에서 매개변수를 사용할 경우 전달하는 값입니다.
- 세번째 파라미터는 언어 설정을 전달합니다.
- Locale.getDefault()메서드는 기본 언어 설정을 가져오는 메서드입니다.
custome 예외 처리
extends 로 다른 예외 처리 상속 받을수 있다
public class ProductNotFoundException extends RuntimeException{
public ProductNotFoundException(String message) {
super(message);
}
}
예제
throw new ProductNotFoundException(
messageSource.getMessage(
"below.min.my.price",
new Integer[]{min_price},
"Wrong Price",
Locale.getDefault() //
)
);
GlobalExceptionHandler 에 적용 예시
@RestControllerAdvice
public class GlobalExceptionHandler {
illigal arugment 일때
@ExceptionHandler({IllegalArgumentException.class})
public ResponseEntity<RestApiException> illegalArgumentExceptionHandler(IllegalArgumentException ex) {
RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
return new ResponseEntity<>(
// HTTP body
restApiException,
// HTTP status code
HttpStatus.BAD_REQUEST
);
}
NullPointerException 일때
@ExceptionHandler({NullPointerException.class})
public ResponseEntity<RestApiException> nullPointerExceptionHandler(NullPointerException ex) {
RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.NOT_FOUND.value());
return new ResponseEntity<>(
// HTTP body
restApiException,
// HTTP status code
HttpStatus.NOT_FOUND
);
}
우리가 만든 Custom Exception 일때 (ProductNotFoundException)
@ExceptionHandler({ProductNotFoundException.class})
public ResponseEntity<RestApiException> notFoundProductExceptionHandler(ProductNotFoundException ex) {
RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.NOT_FOUND.value());
return new ResponseEntity<>(
// HTTP body
restApiException,
// HTTP status code
HttpStatus.NOT_FOUND
);
}
테스트 할때
intellij -> preference -> file encodings
properties 를 UTF-8 로 해야 한글이 된다.