카테고리 없음

Optional.ifPresent, Optional.orElseThrow

문자메일 2023. 8. 24. 06:03

Optional에 값이 없는 경우 기본 값 반환 대신 명시적으로 예외를 던져야 하는 경우 .orElseThrow 사용

값이 있는 경우 사용하고, 없는 경우 사용하고 싶지 않다면 .ifPresent 활용

 

 

// post exist
PostEntity postEntity = postEntityRepository.findById(postId).orElseThrow(()->{
    throw new SnsApplicationException(ErrorCode.POST_NOT_FOUND, String.format("%s not founded", postId));
});

// check liked -> throw
// likeEntityRepository
likeEntityRepository.findByUserAndPost(userEntity, postEntity).ifPresent(it->{
    throw new SnsApplicationException(ErrorCode.ALREADY_LIKED, String.format("userName %s already like post %d", userName, postId));
});

 

https://sin0824.tistory.com/25

 

[Java] Optional<T> isPresent(), ifPresent() 사용하기

Optional을 사용하면 예상치 못한 NullPointerException 예외를 제공되는 메소드로 간단히 회피할 수 있다. 즉, 복잡한 조건문 없이도 널(null) 값으로 인해 발생하는 예외를 처리할 수 있게 된다. 1. isPresen

sin0824.tistory.com

 

https://dev-coco.tistory.com/178

 

[Java] Optional 올바르게 사용하기

개요 Java 언어 설계자인 Brian Goetz는 Optional 을 만든 의도를 다음과 같이 공식 API 문서에 작성해 두었다. API Note: Optional is primarily intended for use as a method return type where there is a clear need to represent "no re

dev-coco.tistory.com