NumberFormatException 에러를 만나고 해결하기

gahyun·2023년 1월 4일
1

Error

목록 보기
1/1
post-thumbnail

발생한 에러

Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "{postsId}"

  • 해석해보자면, String 타입의 데이터를 Long타입으로 변환 실패
    /api/v1/posts/postsId/comments/1
  • URL도 postsId에 데이터를 못가져오는 현상

관련 코드

    @DeleteMapping("/{postsId}/comments/{id}")
    public Response<CommentDeleteResponse> delete(@PathVariable Long postsId,@PathVariable Long id, @ApiIgnore Authentication authentication){
        log.info("댓글 삭제하는 user 이름 {}",authentication.getName());
        log.info("postsId {}",postsId);
        commentService.deleteComment(postsId, id, authentication.getName());
        return Response.success(new CommentDeleteResponse("댓글 삭제 완료",id));
    }

📌 NumberFormatException

설명

  • 숫자 데이터가 아닌 것들이 숫자형으로 변환할 때 발생되는 에러

내가 발생한 원인

    @PostMapping("/{postId}/comments")
    public Response<CommentCreateResponse> create(@RequestBody CommentRequest dto, @PathVariable long postId, @ApiIgnore Authentication authentication){
        log.info("댓글 작성자 이름 {}",authentication.getName());
        return Response.success(commentService.createComment(dto, postId, authentication.getName()));
  • 숫자 데이터형이 아닌것이 변환될 때 오류하고 해서 찾는데 오래걸렸는데 DB를 만들때 나왔던 타입 일치를 시켜줬는지 확인하기!!!

  • db에 데이터를 넣을때, @PathVariable long postId 부분을 Long타입이 아닌 long 타입으로 넣었고 데이터를 다시 사용할때는 Long타입으로 사용해서 변환 오류 발생

해결

  • Long 타입으로 일치시켜주면 해결

0개의 댓글