-
회원정보 수정 4Spring Boot/회원 관리 4 - 회원정보 수정 2021. 12. 13. 17:11
이제는, Optional 처리를 해본다.
만약 서버에서 id =50 인 유저를 데이터베이스에서 찾으려고 하는데,
데이터베이스에 이 유저가 없을 때.
즉, UserService.java 페이지에서 회원수정 메서드에 보면
User userEntity = userRepository.findById(id).get();
이 부분이 있는데,
만약 여기에, id 대신 50을 넣고
@Transactional public User 회원수정(int id, User user) { User userEntity = userRepository.findById(50).get(); userEntity.setName(user.getName()); String rawPassword = user.getPassword(); String encPassword = bCryptPasswordEncoder.encode(rawPassword); userEntity.setPassword(encPassword); userEntity.setBio(user.getBio()); userEntity.setWebsite(user.getWebsite()); userEntity.setPhone(user.getPhone()); userEntity.setGender(user.getGender()); return userEntity; }
사이트에서 회원수정을 해보자. (위의 코드는 사용자가 회원수정 하려고 할 때 실행되는 코드)
그러면 아래 메서드가 실행되기 떄문에,
User userEntity = userRepository.findById(50).get();
이에 대한 결과가 sts(이클립스) 콘솔창에 나오게 된다.
get() 메서드에 문제가 있다는 에러가 나온다.
즉, 데이터베이스에 50번 유저가 없기 때문에 에러가 나오는 것이다.
그래서
get() -> orElseThrow() 변경
orElseThrow() 매개변수로, Supplier 타입을 넣어야 하며 또 그 내부에 IllegalArgumentException 넣음
(illegalArgumentexception)
아무튼, 그래서 이 부분 정리해서 나타내면
@Transactional public User 회원수정(int id, User user) { User userEntity = userRepository.findById(50).orElseThrow(new Supplier<IllegalArgumentException>() { @Override public IllegalArgumentException get() { return new IllegalArgumentException("찾을 수 없는 id 입니다."); } });
(아래 코드는 생략했음)
이렇게 한 다음 회원수정페이지에서 회원정보 수정하면
sts(이클립스) 콘솔창에 에러가 나면서
아래 문구도 같이 나옴
이거를 람다식 이용해서 보기 좋게 하자면,
@Transactional public User 회원수정(int id, User user) { User userEntity = userRepository.findById(50).orElseThrow(() -> {return new IllegalArgumentException("찾을 수 없는 id 입니다.");});
이 오류를, 우리가 지금까지 했던 대로
ControllerExceptionHandler.java 에서 낚아 채서 처리하도록(기존에 만들었던 CustomValidationApiException 사용)
그런데, CustomValidationApiException.java 를 보면
생성자 매개변수로
public CustomValidationApiException(String message, Map<String, String> errorMap) { super(message); this.errorMap = errorMap; }
String message, errorMap 을 받는데,
여기서는 그냥 "찾을 수 없는 id 입니다." 메세지만 보내면 되니깐
생성자를 하나 더 만듦
public CustomValidationApiException(String message) { super(message); }
그러고 나면, 저렇게 잘 받을 수 있고,
ControllerExceptionHandler.java 에서 CustomValiationApiException 을 낚아채는데, 그 부분을 보면
@ExceptionHandler(CustomValidationApiException.class) public ResponseEntity<?> validationApiException(CustomValidationApiException e) { return new ResponseEntity<>(new CMRespDto<>(-1, e.getMessage(), e.getErrorMap()), HttpStatus.BAD_REQUEST); }
이런 식으로 ResponseEntity 로 리턴하니깐,
ajax 입장에서는 update.js 에서 fail 이 실행되고
더보기<update.js> 파일
function update(userId, event) { event.preventDefault(); let data = $("#profileUpdate").serialize(); console.log(data); $.ajax({ type: "put", url : `/api/user/${userId}`, data: data, contentType: "application/x-www-form-urlencoded; charset=utf-8", dataType: "json" }).done(res=>{ console.log("성공", res); location.href = `/user/${userId}`; }).fail(error=>{ alert(JSON.stringify(error.responseJSON.data)); }); }
그 때, 위의 e.getMessage()와 e.getErrorMap 이 같이 날아감
그런데 여기서 e.getErrorMap 이 없으니깐 null 값으로 날아감
그래서 약간 문제가 생기는데,
이 상태까지 마친 다음에
사이트에서 회원정보수정을 실시하면
null 이라는 에러메시지가 사이트화면에 뜨게 된다.
그 이유는 ErrorMap 값이 없어서 그러함.
그런데 update.js 에서는
fail 부분에
.fail(error=>{ alert(JSON.stringify(error.responseJSON.data));
이런식으로, error.responseJSON.data
즉, errorMap 부분을 메세지로 나타내도록 하고 있기 떄문.
null 값인데 화면에 나타내라고 하니 에러가 남
(message는 있음)
그래서
update.js 를 수정하면
.fail(error=>{ if(error.data == null){ alert(error.responseJSON.message); }else{ alert(JSON.stringify(error.responseJSON.data)); } });
이런식으로, 나눠서 처리.
여기서는 errorMap 이 없기 때문에,
(CMRespDto.java 파일에서 errorMap 이 들어가는 위치가 data라는 변수라서 저 코드에서 보면
errorMap 에 값이 없는 것을 error.data == null 이런식으로 표현)
더보기<CMRespDto.java> 파일
@AllArgsConstructor @NoArgsConstructor @Data public class CMRespDto<T> { private int code; private String message; private T data; }
그래서 회원수정 페이지에서 수정한 다음 제출 버튼 누르면
아래와 같이 에러메세지가 잘 나옴
그러면 UserService.java 에서
다시 숫자 50 대신 id 로 변경해서 정리 끝
User userEntity = userRepository.findById(id).orElseThrow(() -> {return new CustomValidationApiException("찾을 수 없는 id 입니다.");});
참고 자료 : 이지업 강의 사이트 "스프링부트 SNS프로젝트 - 포토그램 만들기"
'Spring Boot > 회원 관리 4 - 회원정보 수정' 카테고리의 다른 글
회원정보 수정 3 (0) 2021.12.12 회원정보 수정 2 (0) 2021.12.11 회원정보 수정 1 (0) 2021.12.11