TIL)23.08.25(매개변수 null)

주민·2023년 8월 27일
0

TIL

목록 보기
72/84

문제

s3을 만들면서 MultipartFile을 받지 않아도 post를 만들 수 있도록 controller에 "required = false" 옵션도 줬는데 아래와 같은 오류가 났다.

2023-08-28T01:32:26.027+09:00 ERROR 19376 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.NullPointerException: Cannot invoke "java.util.List.iterator()" because "files" is null] with root cause

  • service 코드
for (MultipartFile file : files) {
    if (file != null) {
        String fileUrl = imageService.upload(file,  "post " + post.getId());
        if (imageRepository.existsByImageUrlAndId(fileUrl, post.getId())) {
            throw new BusinessException(ErrorCode.EXISTED_FILE);
        }
        imageRepository.save(new Image(post, fileUrl));
    }
}

시도 & 해결

s3 upload 부분 로직 문제인가 해서 다른 블로그에 있는 내용대로 다 수정했는데도 동일한 오류가 났다. 오류 내용 검색하던 중 null 체크를 해줘야 한다는 부분이 있어 혹시 싶어 if/for문의 위치를 바꿔보니 해결됐다.

if (files != null) {
    for (MultipartFile file : files) {
        String fileUrl = imageService.upload(file, "post " + post.getId());
        if (imageRepository.existsByImageUrlAndId(fileUrl, post.getId())) {
            throw new BusinessException(ErrorCode.EXISTED_FILE);
        }
        imageRepository.save(new Image(post, fileUrl));
    }
}

매개변수로 받은 이미지 파일이 리스트여서 files > file로 반복문을 돌리고 null 체크를 했는데 required = false 옵션이 들어간 매개변수는 file이 아닌 files 이니 null 체크를 하고 for문 돌리는 것이 맞았다.

알게된 점

  • controller에서 required = false 욥션을 주면 빈값으로 받아도 실행이 가능하다.
    @RequestParam(required = false) List files
    => 다만, 값이 있을 경우와 없을 경우에 로직이 다르기 때문에 null 체크해야하며 체크 값은 무조건 매개변수로 받은 값으로 해야한다.

0개의 댓글

관련 채용 정보