WEB ( Back, Front)/Spring
@RequestParam 값이 Null 일 때, 예외 처리하는 방법
프리랜서가 들려주는 IT세계
2021. 6. 16. 14:23
반응형
서비스를 운영하거나,
개발을 하면서 파라미터(Parameter)로 받을 값을 필수 값을 처리하는 경우가 있었다.
예를 들어
@RequestParam(value = "token", required = true) String token
이와같이 처리하게 된다면,
parameter를 아무것도 입력 안했을 시,
spring에서
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'token' is not present
이와 같은 에러를 내보내게 될 것이다.
이부분을 예외처리하고 싶다면
이와 같이 행동해라!
1. required = false로 처리하기!
@RequestParam(value = "token", required = false) String token
false를 하게 된다면, 위와 같은 에러를 보내지 않게 된다.
2. if로 Requestparameter값 유무값 체크하기
if(StringUtils.isEmpty(token) {
thorw new "예외처리할 내용";
}
그리고 로직안에 if로 token값을 체크해준다.
그리고 throw로 예외처리한다.
이와같이 처리를 한다면 보내고 싶은 예외 처리가 가능하다.
감사합니다.
반응형