회원 가입 로직 구현

https://github.com/beginner0107/bank/commit/dae1a571b4082f3db78e81c2dc1a6e5baac60c62

1. 동일한 사용자가 존재하는지 확인
중복 사용자인 경우 오류 `CustomApiException던지다`
2. 암호 암호화(같은 방법으로)
삼. JoinRespDto답장하기

  • REST API에서 오류를 처리할 때
@RestControllerAdvice
public class CustomExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(CustomApiException.class)
    public ResponseEntity<?> apiException(CustomApiException e) {
        log.error(e.getMessage());
        return new ResponseEntity<>(new ResponseDto<>(-1, e.getMessage(), null), HttpStatus.BAD_REQUEST);
    }
}
  • @RestControllerAdvice : 주석 사용
  • @ExceptionHandler에 사용자 지정 예외가 있는 경우
  • 현재 내가 만든 CustomApiException이 발생하면 여기에서 오류를 확인하겠습니다.
  • Json 형식으로 ResponseEntity를 반환합니다.

CustomApiException

public class CustomApiException extends RuntimeException{

    public CustomApiException(String message) {
        super(message);
    }
}

  • 현재 회원 관련 서비스 담당 사용자 서비스

@RequiredArgsConstructor
@Service
public class UserService {
    private final Logger log = LoggerFactory.getLogger(getClass());
    private final UserRepository userRepository;
    private final BCryptPasswordEncoder passwordEncoder;

    // 서비스는 DTO를 요청받고, DTO로 응답한다.
    @Transactional // 트랜잭션이 메서드 시작할 때, 시작되고, 종료될 때 함께 종료
    public JoinRespDto 회원가입(JoinReqDto joinReqDto) {
        // 1. 동일 유저네임 존재 검사
        Optional<User> userOP = userRepository.findByUsername(joinReqDto.getUsername());
        if (userOP.isPresent()) {
            // 유저네임 중복되었다는 뜻
            throw new CustomApiException("동일한 username이 존재합니다.");
        }

        // 2. 패스워드 인코딩
        User userPS = userRepository.save(joinReqDto.toEntity(passwordEncoder));

        // 3. dto 응답
        return new JoinRespDto(userPS);
    }

    @Getter
    @Setter
    public static class JoinRespDto {
        private Long id;
        private String username;
        private String fullname;

        public JoinRespDto(User user) {
            this.id = user.getId();
            this.username = user.getUsername();
            this.fullname = user.getFullname();
        }
    }

    @Getter
    @Setter
    public static class JoinReqDto {
        // 유효성 검사
        private String username;
        private String password;
        private String email;
        private String fullname;

        public User toEntity(BCryptPasswordEncoder passwordEncoder) {
            return User.builder()
                    .username(username)
                    .password(passwordEncoder.encode(password))
                    .email(email)
                    .fullname(fullname)
                    .role(UserEnum.CUSTOMER)
                    .build();
        }
    }
}
  • 중복 멤버 이름이 발견되면 new throw CustomApiException던지는 것을 볼 수 있다