[Spring/개발] - TMI(5)

동글이·2022년 9월 19일
0

Spring/개발

목록 보기
7/7

에러 모음

  • 415 : 포스트맨(클라이언트) 에서 주는 형식이 잘못됨
  • 404 : 지정된 주소를(url) 컨트롤러에서 찾을 수 없음

예외처리

@PostMapping("/user")
    public ResponseEntity<BaseResponseBody> signup (@RequestBody SignupDTO signupDTO){
        BaseResponseBody responseBody = new BaseResponseBody("회원가입 성공");
        try {
            userService.signUp(signupDTO);
        } catch (IllegalStateException e){
            responseBody.setResultCode(-1);     //클라이언트 잘못
            responseBody.setResultMsg(e.getMessage());
            return ResponseEntity.ok().body(responseBody);      //에러 코드 400 => 클라이언트 잘못
        } catch (Exception e){
            responseBody.setResultCode(-2);     //내 코드 잘못
            responseBody.setResultMsg(e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseBody);      //에러 코드 500 => 서버 잘못
        }
        return ResponseEntity.ok().body(responseBody);
    }
@Transactional(readOnly = false)
    public User signUp(SignupDTO signupDTO) {
        User user = new User();
        if (signupDTO.getName().isBlank()) {
            throw new IllegalStateException("이름이 유효하지 않습니다.");
        }
        if (signupDTO.getNickname().isBlank()) {
            throw new IllegalStateException("닉네임이 유효하지 않습니다.");
        }
        if (!isValidEmailAddress(signupDTO.getEmail())) {
            throw new IllegalStateException("이메일 형식이 유효하지 않습니다.");
        }
        if(isDuplicateEmail(signupDTO.getEmail())){
            throw new IllegalStateException("이메일이 중복됩니다.");
        }
        if (signupDTO.getJobLevel() < 1 || signupDTO.getJobLevel() > 5) {
            throw new IllegalStateException("직무 숙련도가 유효하지 않습니다.");
        }
        if (signupDTO.getJob().isBlank()) {
            throw new IllegalStateException("직무 이름이 유효하지 않습니다.");
        }
        if (signupDTO.getUserSkills().isEmpty()) {
            throw new IllegalStateException("스킬을 입력해주세요");
        }
        // 유저 정보 저장
        user.setName(signupDTO.getName());
        user.setNickname(signupDTO.getNickname());
        user.setEmail(signupDTO.getEmail());
        user.setPassword(getEncryptPassword(signupDTO.getPassword()));
        user.setJob(signupDTO.getJob());
        user.setJobLevel(signupDTO.getJobLevel());
        user.setIsReceiveMail(signupDTO.getIsReceiveMail());
        user.setSelfIntro(signupDTO.getSelfIntro());
        userRepository.save(user);
        // 유저 스킬 저장
        for (UserSkillDTO userSkillDTO : signupDTO.getUserSkills()) {
            UserSkill userSkill = new UserSkill();
            userSkill.setUser(user);
            userSkill.setName(userSkillDTO.getName());
            userSkill.setLevel(userSkillDTO.getLevel());
            userSkillRepository.save(userSkill);
        }
        return user;
    }

enum 과 문자열 비교

에는 valueof 이걸 쓰자!
예시)

project.getStatus().equals(ProjectStatus.valueOf("PROGRESS"))
profile
기죽지 않는 개발자

0개의 댓글