Skip to content

Commit 7886c87

Browse files
committed
Feat : 적절한 예외를 반환하도록 변경
1 parent 9465876 commit 7886c87

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

back/src/main/java/com/back/domain/news/comment/service/CommentService.java

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@
55
import com.back.domain.news.comment.repository.CommentRepository;
66
import com.back.domain.news.news.entity.News;
77
import lombok.RequiredArgsConstructor;
8+
import org.springframework.security.access.AccessDeniedException;
89
import org.springframework.stereotype.Service;
910
import org.springframework.transaction.annotation.Transactional;
1011

1112
import java.util.List;
12-
import java.util.Optional;
13+
import java.util.NoSuchElementException;
1314

1415
@Service
1516
@RequiredArgsConstructor
@@ -26,14 +27,16 @@ public List<Comment> getComments(News news) {
2627
return commentRepository.findByNews(news);
2728
}
2829

29-
public Optional<Comment> getCommentById(Long commentId) {
30-
return commentRepository.findById(commentId);
30+
public Comment getCommentById(Long commentId) {
31+
return commentRepository.findById(commentId)
32+
.orElseThrow(() -> new NoSuchElementException("Comment not found: " + commentId));
3133
}
3234

3335
public Comment updateComment(Member member, News news, Long commentId, String content) {
34-
Comment comment = getCommentById(commentId).orElseThrow(() -> new IllegalArgumentException("Comment not found"));
36+
Comment comment = getCommentById(commentId);
37+
3538
if (!comment.getMember().equals(member)) {
36-
throw new IllegalArgumentException("You do not have permission to update this comment.");
39+
throw new AccessDeniedException("You do not have permission to update this comment.");
3740
}
3841
if (!comment.getNews().equals(news)) {
3942
throw new IllegalArgumentException("This comment does not belong to the given news.");
@@ -43,9 +46,10 @@ public Comment updateComment(Member member, News news, Long commentId, String co
4346
}
4447

4548
public void deleteComment(Member member, News news, Long commentId) {
46-
Comment comment = getCommentById(commentId).orElseThrow(() -> new IllegalArgumentException("Comment not found"));
49+
Comment comment = getCommentById(commentId);
50+
4751
if (!comment.getMember().equals(member)) {
48-
throw new IllegalArgumentException("You do not have permission to delete this comment.");
52+
throw new AccessDeniedException("You do not have permission to delete this comment.");
4953
}
5054
if (!comment.getNews().equals(news)) {
5155
throw new IllegalArgumentException("This comment does not belong to the given news.");

0 commit comments

Comments
 (0)