Skip to content

Commit

Permalink
Merge pull request #92 from IxxP-Girls/modify
Browse files Browse the repository at this point in the history
Feat: ExceptionHandler 이용해 예외처리
  • Loading branch information
diddnwjd authored Mar 7, 2024
2 parents c782b4c + c7ef8bc commit bbd12f4
Show file tree
Hide file tree
Showing 7 changed files with 130 additions and 35 deletions.
5 changes: 3 additions & 2 deletions src/main/java/com/ixxp/culpop/service/AdminService.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.ixxp.culpop.util.jwtutil.JwtUtil;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -39,11 +40,11 @@ public void loginAdmin(AdminLoginRequest adminLoginRequest, HttpServletResponse

Admin admin = adminMapper.selectEmail(email);
if (admin == null) {
throw new IllegalArgumentException("해당 email 이 존재하지 않습니다.");
throw new UsernameNotFoundException("해당 email 이 존재하지 않습니다.");
}

if (!passwordEncoder.matches(pwd, adminMapper.selectEmail(email).getPwd())) {
throw new IllegalArgumentException("비밀번호가 일치하지 않습니다.");
throw new BadCredentialsException("비밀번호가 일치하지 않습니다.");
}

// accessToken 생성
Expand Down
36 changes: 20 additions & 16 deletions src/main/java/com/ixxp/culpop/service/CommentService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@
import com.ixxp.culpop.mapper.CommentMapper;
import com.ixxp.culpop.mapper.PostMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Service
Expand All @@ -28,7 +32,7 @@ public class CommentService {
public void createComment(User user, int postId, CommentRequest commentRequest) {
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}

Comment comment = new Comment(user, post, commentRequest.getContent(), commentRequest.isSecret(), commentRequest.getParentId());
Expand All @@ -40,7 +44,7 @@ public List<CommentResponse> getComment(User user, int postId, int page) {
// 게시글 존재 확인
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}

// 게시글에 딸린 댓글 리스트 조회
Expand Down Expand Up @@ -71,16 +75,16 @@ public List<CommentResponse> getComment(User user, int postId, int page) {
public void updateComment(User user, int postId, int commentId, CommentRequest commentRequest) {
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}

Comment comment = commentMapper.selectCommentDetail(commentId);
if (comment == null) {
throw new IllegalArgumentException("comment가 존재하지 않습니다.");
throw new EntityNotFoundException("comment가 존재하지 않습니다.");
}

if (comment.getUser().getId() != user.getId()) {
throw new IllegalArgumentException("작성자만 수정 가능합니다.");
throw new AccessDeniedException("작성자만 수정 가능합니다.");
}

comment.updateComment(user, post, commentRequest.getContent(), commentRequest.isSecret(), commentRequest.getParentId());
Expand All @@ -93,16 +97,16 @@ public void updateComment(User user, int postId, int commentId, CommentRequest c
public void deleteComment(User user, int postId, int commentId) {
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}

Comment comment = commentMapper.selectCommentDetail(commentId);
if (comment == null) {
throw new IllegalArgumentException("comment가 존재하지 않습니다.");
throw new EntityNotFoundException("comment가 존재하지 않습니다.");
}

if (comment.getUser().getId() != user.getId()) {
throw new IllegalArgumentException("작성자만 수정 가능합니다.");
throw new AccessDeniedException("작성자만 수정 가능합니다.");
}

if (comment.getPost().getId() != postId) {
Expand All @@ -117,20 +121,20 @@ public void deleteComment(User user, int postId, int commentId) {
public void likeComment(User user, int postId, int commentId) {
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}

Comment comment = commentMapper.selectCommentDetail(commentId);
if (comment == null) {
throw new IllegalArgumentException("comment가 존재하지 않습니다.");
throw new EntityNotFoundException("comment가 존재하지 않습니다.");
}

if (comment.getPost().getId() != postId) {
throw new IllegalArgumentException("post를 잘못 입력하였습니다.");
throw new EntityNotFoundException("post를 잘못 입력하였습니다.");
}

if (commentLikeMapper.checkCommentLike(user.getId(), commentId)) {
throw new IllegalArgumentException("이미 좋아요를 눌렀습니다.");
throw new DuplicateKeyException("이미 좋아요를 눌렀습니다.");
}

CommentLike commentLike = new CommentLike(user, comment);
Expand All @@ -142,20 +146,20 @@ public void likeComment(User user, int postId, int commentId) {
public void unlikeComment(User user, int postId, int commentId) {
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}

Comment comment = commentMapper.selectCommentDetail(commentId);
if (comment == null) {
throw new IllegalArgumentException("comment가 존재하지 않습니다.");
throw new EntityNotFoundException("comment가 존재하지 않습니다.");
}

if (comment.getPost().getId() != postId) {
throw new IllegalArgumentException("post를 잘못 입력하였습니다.");
throw new EntityNotFoundException("post를 잘못 입력하였습니다.");
}

if (!commentLikeMapper.checkCommentLike(user.getId(), commentId)) {
throw new IllegalArgumentException("댓글 좋아요를 누르지 않았습니다.");
throw new NoSuchElementException("댓글 좋아요를 누르지 않았습니다.");
}

CommentLike commentLike = new CommentLike(user, comment);
Expand Down
13 changes: 8 additions & 5 deletions src/main/java/com/ixxp/culpop/service/PopupService.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@
import com.ixxp.culpop.mapper.*;
import lombok.RequiredArgsConstructor;
import org.json.simple.JSONArray;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Service
Expand Down Expand Up @@ -200,7 +203,7 @@ public List<PopupResponse> convertToPopupResponseList(User user, List<Popup> pop
private Popup getValidPopup(int popupId) {
Popup popup = popupMapper.selectPopup(popupId);
if (popup == null) {
throw new IllegalArgumentException("Popup이 존재하지 않습니다.");
throw new EntityNotFoundException("Popup이 존재하지 않습니다.");
}
return popup;
}
Expand Down Expand Up @@ -243,7 +246,7 @@ private int getViewCountByPopupId(int popupId) {

private void validateAdmin(Popup popup, Admin admin) {
if (popup.getAdmin().getId() != admin.getId()) {
throw new IllegalArgumentException("작성자만 수정 가능합니다.");
throw new AccessDeniedException("작성자만 수정 가능합니다.");
}
}

Expand All @@ -270,13 +273,13 @@ private void deletePopupTagsAndTags(List<PopupTag> popupTags, Popup popup) {

private void validatePopupLike(User user, int popupId) {
if (popupLikeMapper.checkPopupLike(user.getId(), popupId)) {
throw new IllegalArgumentException("이미 좋아요를 눌렀습니다.");
throw new DuplicateKeyException("이미 좋아요를 눌렀습니다.");
}
}

private void validatePopupUnlike(User user, int popupId) {
if (!popupLikeMapper.checkPopupLike(user.getId(), popupId)) {
throw new IllegalArgumentException("팝업 좋아요를 누르지 않았습니다.");
throw new NoSuchElementException("팝업 좋아요를 누르지 않았습니다.");
}
}
}
22 changes: 13 additions & 9 deletions src/main/java/com/ixxp/culpop/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,14 @@
import com.ixxp.culpop.mapper.PostLikeMapper;
import com.ixxp.culpop.mapper.PostMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -54,7 +58,7 @@ public List<PostResponse> getPost(String category, int page) {
public PostDetailResponse getPostDetail(User user, int postId) {
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}

boolean likeCheck = (user != null) && postLikeMapper.checkPostLike(user.getId(), postId);
Expand All @@ -74,11 +78,11 @@ public PostDetailResponse getPostDetail(User user, int postId) {
public void updatePost(User user, int postId, PostRequest postRequest) {
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}

if (post.getUser().getId() != user.getId()) {
throw new IllegalArgumentException("작성자만 수정 가능합니다.");
throw new AccessDeniedException("작성자만 수정 가능합니다.");
}

String cateName = postRequest.getCateName();
Expand All @@ -100,11 +104,11 @@ public void updatePost(User user, int postId, PostRequest postRequest) {
public void deletePopup(User user, int postId) {
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}

if (post.getUser().getId() != user.getId()) {
throw new IllegalArgumentException("작성자만 수정 가능합니다.");
throw new AccessDeniedException("작성자만 수정 가능합니다.");
}

postMapper.deletePost(postId);
Expand All @@ -115,10 +119,10 @@ public void deletePopup(User user, int postId) {
public void likePost(User user, int postId) {
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}
if (postLikeMapper.checkPostLike(user.getId(), postId)) {
throw new IllegalArgumentException("이미 좋아요를 눌렀습니다.");
throw new DuplicateKeyException("이미 좋아요를 눌렀습니다.");
}

PostLike postLike = new PostLike(user, post);
Expand All @@ -130,10 +134,10 @@ public void likePost(User user, int postId) {
public void unlikePost(User user, int postId) {
Post post = postMapper.selectPostDetail(postId);
if (post == null) {
throw new IllegalArgumentException("post가 존재하지 않습니다.");
throw new EntityNotFoundException("post가 존재하지 않습니다.");
}
if (!postLikeMapper.checkPostLike(user.getId(), postId)) {
throw new IllegalArgumentException("좋아요를 누르지 않았습니다.");
throw new NoSuchElementException("좋아요를 누르지 않았습니다.");
}

PostLike postLike = new PostLike(user, post);
Expand Down
7 changes: 4 additions & 3 deletions src/main/java/com/ixxp/culpop/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseCookie;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand Down Expand Up @@ -61,11 +62,11 @@ public void login(UserLoginRequest userLoginRequest, HttpServletResponse respons
User user = userMapper.selectEmail(email);

if (user == null) {
throw new IllegalArgumentException("해당 email 이 존재하지 않습니다.");
throw new UsernameNotFoundException("해당 email 이 존재하지 않습니다.");
}

if (!passwordEncoder.matches(pwd, user.getPwd())) {
throw new IllegalArgumentException("비밀번호가 일치하지 않습니다.");
throw new BadCredentialsException("비밀번호가 일치하지 않습니다.");
}

// accessToken 생성
Expand Down
13 changes: 13 additions & 0 deletions src/main/java/com/ixxp/culpop/util/exception/RestApiException.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
package com.ixxp.culpop.util.exception;

import lombok.Getter;
import org.springframework.http.HttpStatus;

@Getter
public class RestApiException {
private final HttpStatus status;
private final String errorCode;
private final String errorMessage;

public RestApiException(HttpStatus status, String errorCode, String errorMessage) {
this.status = status;
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,73 @@
package com.ixxp.culpop.util.exception;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.persistence.EntityNotFoundException;
import java.util.NoSuchElementException;

@ControllerAdvice
public class RestApiExceptionHandler {
// 회원가입 - email 중복
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<?> handleIllegalArgumentException(IllegalArgumentException e) {
RestApiException errorResponse = new RestApiException(HttpStatus.BAD_REQUEST, "400", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
}

// 로그인 - email 없음
@ExceptionHandler(UsernameNotFoundException.class)
public ResponseEntity<?> handleUsernameNotFoundException(UsernameNotFoundException e) {
RestApiException errorResponse = new RestApiException(HttpStatus.UNAUTHORIZED, "401", e.getMessage());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorResponse);
}

// 로그인 - 비밀번호 불일치
@ExceptionHandler(BadCredentialsException.class)
public ResponseEntity<?> handleBadCredentialsException(BadCredentialsException e) {
RestApiException errorResponse = new RestApiException(HttpStatus.UNAUTHORIZED, "401", e.getMessage());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorResponse);
}

// 팝업의 time 을 json 으로 변환 실패
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<?> handleRuntimeException(RuntimeException e) {
RestApiException errorResponse = new RestApiException(HttpStatus.INTERNAL_SERVER_ERROR, "500", e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
}

// 팝업, 게시글, 댓글 없음
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<?> handleEntityNotFoundException(EntityNotFoundException e) {
RestApiException errorResponse = new RestApiException(HttpStatus.NOT_FOUND, "404", e.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
}

// 작성자만 수정 가능
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<?> handleAccessDeniedException(AccessDeniedException e) {
RestApiException errorResponse = new RestApiException(HttpStatus.FORBIDDEN, "403", e.getMessage());
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
}

// 좋아요 중복
@ExceptionHandler(DuplicateKeyException.class)
public ResponseEntity<?> handleDuplicateKeyException(DuplicateKeyException e) {
RestApiException errorResponse = new RestApiException(HttpStatus.CONFLICT, "409", e.getMessage());
return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse);
}

// 좋아요 없음
@ExceptionHandler(NoSuchElementException.class)
public ResponseEntity<?> handleNoSuchElementException(NoSuchElementException e) {
RestApiException errorResponse = new RestApiException(HttpStatus.BAD_REQUEST, "400", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
}
}

0 comments on commit bbd12f4

Please sign in to comment.