
스프링이 직접 만든 오류 메시지 처리 검증 오류 코드는 다음과 같이 2가지로 나눌 수 있다. 실행해서 이렇게 해놓고 콘솔 로그 보면 메시지는 이런 식으로 나타나고 잇음. 즉, 다음과 같이 4개의 메시지 코드가 나타나고 있다. 실행해보면 아직 errors.properties 에 메시지 코드가 없기 때문에 스프링이 생성한 기본 메시지가 출력된다. Failed to convert property value of type java.lang.String to required type java.lang.Integer for property price; nested exception is java.lang.NumberFormatException: For input string: "qqqq" errors.propert..

오류 코드 관리 전략 만들기 시작 errors.properties #required.item.itemName=상품 이름은 필수입니다. #range.item.price=가격은 {0} ~ {1} 까지 허용합니다. #max.item.quantity=수량은 최대 {0} 까지 허용합니다. #totalPriceMin=가격 * 수량의 합은 {0}원 이상이어야 합니다. 현재 값 = {1} #==ObjectError== #Level1 totalPriceMin.item=상품의 가격 * 수량의 합은 {0}원 이상이어야 합니다. 현재 값 = {1} #Level2 - 생략 totalPriceMin=전체 가격은 {0}원 이상이어야 합니다. 현재 값 = {1} #==FieldError== #Level1 required.item.i..

먼저 이렇게 찍어보면 두 가지 메시지 코드를 나타낸다. 두 번째 테스트 찍어보면 결과로 4개를 출력한다. 가장 디테일한 게 첫 번째로, 가장 포괄적인게 마지막으로 나온다. 전체 코드 package hello.itemservice.validation; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.validation.DefaultMessageCodesResolver; import org.springframework.validation.MessageCodesResolver; import static org.assertj.core.api.Assertions.assertTha..

오류 코드와 메시지 처리 (2) 목표 FieldError , ObjectError 는 다루기 너무 번거롭다. 오류 코드도 좀 더 자동화 할 수 있지 않을까? 예) item.itemName 처럼? 컨트롤러에서 BindingResult 는 검증해야 할 객체인 target 바로 다음에 온다. 따라서 BindingResult 는 이미 본인이 검증해야 할 객체인 target 을 알고 있다. 로그 코드를 앞선 메서드에 추가해서 결과를 확인해본다. @PostMapping("/add") public String addItemV3(@ModelAttribute Item item, BindingResult bindingResult, RedirectAttributes redirectAttributes) { // 요기 추가 l..

오류 코드와 메시지 처리 (1) 목표 오류 메시지를 체계적으로 다루어보기. FieldError 생성자 FieldError 는 두 가지 생성자를 제공한다. FieldError , ObjectError 의 생성자는 codes , arguments 를 제공한다. 이것은 오류 발생시 오류 코드로 메시지를 찾기 위해 사용된다. errors 메시지 파일 생성 messages.properties 를 사용해도 되지만, 오류 메시지를 구분하기 쉽게 errors.properties 라는 별도의 파일로 관리해보자. * 먼저 스프링 부트가 해당 메시지 파일을 인식할 수 있게 다음 설정을 추가한다. 이렇게 하면 messages.properties , errors.properties 두 파일을 모두 인식한다. (생략하면 mess..

FieldError, ObjectError 목표 사용자 입력 오류 메시지가 화면에 남도록 하자. 예) 가격을 1000원 미만으로 설정시 입력한 값이 남아있어야 한다. FieldError , ObjectError 에 대해서 더 자세히 알아본다. ValidationItemControllerV2 - addItemV2 새 메서드 구현 (기존 V1은 주석처리) 실행해서 에러를 내보면 빨간색 오류메시지가 나와도 내용이 그대로 유지되고 있음을 확인할 수 있다. 하나씩 살펴보기 1. 필드 검증 2. 전체 예외 # FieldError의 두 가지 생성자 # ObjectError 도 두 가지 생성자 # 오류 발생시 사용자 입력 값 유지 new FieldError("item", "price", item.getPrice(), ..

BindingResult 두 번째 스프링이 제공하는 검증 오류를 보관하는 객체이다. 검증 오류가 발생하면 여기에 보관하면 된다. BindingResult 가 있으면 @ModelAttribute 에 데이터 바인딩 시 오류가 발생해도 컨트롤러가 호출된다! ~~~~~ errors=org.springframework.validation.BeanPropertyBindingResult: 2 errors Field error in object 'item' on field 'price': rejected value [yyyy]; codes [typeMismatch.item.price,typeMismatch.price,typeMismatch.java.lang.Integer,typeMismatch]; arguments [..