Skip to content

[BE, #2] 날짜 문자열 변환 오류로 인한 400 에러 발생

Hyeok-Gyu Lee edited this page Mar 21, 2024 · 1 revision

날짜 : 2024.03.21


🚨 문제 상황

  • 프론트에서 submit을 눌렀을 때, White Error Page가 뜬다 : There was an unexpected error (type=Bad Request, status=400)

    @PostMapping("/challenge/create_form")
      public String createChallenge(@ModelAttribute ChallengeDTO challengeDTO, RedirectAttributes redirectAttributes) {
          log.info(challengeDTO.toString());
          Challenge challenge = challengeDTO.toEntity();
          Challenge saved = challengeRepository.save(challenge);
          log.info(saved.toString());
          redirectAttributes.addAttribute("challenge_id", saved.getChallenge_id());
          return "redirect:/challenge/success";
      }



💡 문제 원인 및 해결 과정

원인

  • 메서드 인자의 유효성 검사를 통과하지 못했다 !

    org.springframework.web.bind.MethodArgumentNotValidException
  • 날짜를 String type으로 전달해주었는데, 이를 Date type으로 변환시키지 못해 발생한 에러이다.

    Field error in object 'challengeDTO' on field 'end_date'
    Field error in object 'challengeDTO' on field 'start_date'

해결

  • 여러 방법이 있겠지만, ChallengeDTO의 start_date, end_date를 String type으로 변환한 후, toEntity 함수에서 parseDateString를 적용해 Date type으로 바꾸어 주었다.

      private Date parseDateString(String dateString) {
          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
          try {
              return simpleDateFormat.parse(dateString);
          } catch (ParseException e) {
              return null;
          }
      }