V2.6 Spring 기본 오류 코드 변경

알파로그·2023년 3월 26일
0

Spring MVC 활용 기술

목록 보기
40/42

✏️ 검증 오류 코드의 분류

  1. 개발자가 직접 정의한 오류코드
    • rejectValue() 를 직접 호출
  2. Spring 이 직접 검증 오류에 추가한 오류 코드
    • type 오류가 여기에 해당됨

✏️ type 오류 메시지 처리하기

📍 type 오류 코드 확인하기

  • type 이 일치하지 않아 오류가 발생될 경우,
    콘솔을 확인하면 어떤 오류코드가 실행됬는지 확인할 수 있다.
Field error in object 'item' on field 'price'
	: rejected value []; codes [typeMismatch.item.price,typeMismatch.price,typeMismatch.java.lang.Integer,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [item.price,price]; arguments []; default message [price]]; default message [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: "ㅂ"]
  • 메시지를 잘 보면 codes 문구를 찾을 수있고 그 뒤로 코드명이 적혀있다.
    • 이런 오류코드가 총 4개가 적혀있다.
    • 자세히 보니 Message Codes Resolver 의 필드 오류의 반환값과 구조가 동일하다.
    • 🔗 Message Codes Resolver
codes [typeMismatch.item.price ...

#-- 정리 --#
- typeMismatch.item.price
- typeMismatch.price
- typeMismatch.java.lang.Integer
- typeMismatch

📍 오류코드 추가

  • 이렇게 찾아낸 오류코드를 우리가 만든 메시지 파일에 추가해주면 원하는 메시지를 출력시킬 수 있다.
    • error properties
      • 4개중 아무거나 선택해도 되지만 그냥 가장 낮은 레벨의 코드를 선택했다.
      • 수량도 type 오류가 발생할 수 있어 2개의 코드를 추가해주었다.
# type 오류 추가
typeMismatch.item.price=가격은 숫자를 입력해야 합니다.
typeMismatch.item.quantity=수량은 숫자를 입력해야 합니다.
profile
잘못된 내용 PR 환영

0개의 댓글