Spring/팀스파르타

51. Spring의 properties 파일을 이용한 에러 메시지 관리

열심히 해 2024. 12. 9. 17:32

 

Spring의 properties 파일을 이용한 에러 메시지 관리

  • Spring에서는 properties 파일을 이용하여 에러 메시지를 관리할 수 있습니다.
  • 에러 메시지는 properties 파일에서 key-value 형태로 작성되며, 작성된 값은 messageSource 를 Bean으로 등록하여 사용할 수 있습니다.

 

 

resources/messages.properties.file

below.min.my.price=최저 희망가는 최소 {0}원 이상으로 설정해 주세요.
not.found.product=해당 상품이 존재하지 않습니다.

 

 

private final MessageSource messageSource;

...

@Transactional
public ProductResponseDto updateProduct(Long id, ProductMypriceRequestDto requestDto) {
    int myprice = requestDto.getMyprice();
    if (myprice < MIN_MY_PRICE) {
        throw new IllegalArgumentException(
                messageSource.getMessage(
                        "below.min.my.price", // properties에 설정해놓은 놓은 code
                        new Integer[]{MIN_MY_PRICE},
                        "Worng Price",
                        Locale.getDefault() // 언어 설정
                )
        );
    }

    Product product = productRepository.findById(id).orElseThrow(() ->
            new ProductNotFoundException(messageSource.getMessage(
                    "not.found.product",
                    null,
                    "Not Found Product",
                    Locale.getDefault()
            ))
    );

    product.update(requestDto);

    return new ProductResponseDto(product);
}

 

messageSource.getMessage()메서드

  • 첫 번째 파라미터는 messages.properties 파일에서 가져올 메시지의 키 값을 전달합니다.
  • 두 번째 파라미터는 메시지 내에서 매개변수를 사용할 경우 전달하는 값입니다.
  • 세 번째 파라미터는 디폴트 메시지입니다.
  • 네 번째 파라미터는 언어 설정을 전달합니다.
  • Locale.getDefault()메서드는 기본 언어 설정을 가져오는 메서드입니다.

 

 

Exception 클래스를 직접 구현하여 사용할 수도 있습니다.

public class ProductNotFoundException extends RuntimeException {
    public ProductNotFoundException(String message) {
        super(message);
    }
}

 

@RestControllerAdvice
public class GlobalExceptionHandler {

    @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
        );
    }

    @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
        );
    }

    @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
        );
    }
}

RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.NOT_FOUND.value());
        return new ResponseEntity<>(
                // HTTP body
                restApiException,
                // HTTP status code
                HttpStatus.NOT_FOUND
        );

 

1. new RestApiException()  생성자 호출하며 넣어주는 HttpStatus.NOT_FOUND.value() 는 클라이언트가 응답에서 바로 확인할 수 있게 해줍니다.

 

2. 그 아래에 있는 new ResponseEntity<>() 인자로 있는 HttpStatus.NOT_FOUND는 DevTool 에서 상태 코드(404)를 명시해줍니다.

 

 

 

 

 

ResponseEntity 에 관한 포스팅: 

 

https://tes1194.tistory.com/98