Skip to content

Commit

Permalink
[#112] 리팩토링
Browse files Browse the repository at this point in the history
- 팔로우 기능 예외 처리 수정
  • Loading branch information
JAEHEE25 committed Dec 3, 2024
1 parent 536e852 commit e2a4e46
Show file tree
Hide file tree
Showing 14 changed files with 59 additions and 46 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package io.driver.codrive.global.exception;

public class NotFoundApplicationException extends ApplicationException {
public NotFoundApplicationException(String message) {
super(ErrorType.NOT_FOUND, message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@
import java.util.HashMap;
import java.util.Map;

import org.hibernate.StaleStateException;
import org.hibernate.dialect.lock.OptimisticEntityLockException;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
Expand Down Expand Up @@ -41,4 +45,10 @@ public ResponseEntity<ErrorResponse> handleException(Exception e, HttpServletReq
log.error("Request: {} {}, Exception: {}", request.getMethod(), request.getRequestURI(), e.getMessage(), e);
return new ResponseEntity<>(ErrorResponse.of(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), null), HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(ConcurrencyFailureException.class)
public ResponseEntity<ErrorResponse> handleStaleStateException(ConcurrencyFailureException e, HttpServletRequest request) {
log.error("Request: {} {}, ConcurrencyFailureException: {}", request.getMethod(), request.getRequestURI(), e.getMessage(), e);
return new ResponseEntity<>(ErrorResponse.of(HttpStatus.INTERNAL_SERVER_ERROR.value(), "요청을 처리할 수 없습니다.", null), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@
public interface FollowRepository extends JpaRepository<Follow, Long>, FollowRepositoryCustom {

Optional<Follow> findByFollowingAndFollower(User following, User follower);

boolean existsByFollowingAndFollower(User following, User follower);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,21 @@
import java.util.Comparator;
import java.util.List;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.driver.codrive.global.exception.InternalServerErrorApplicationException;
import io.driver.codrive.global.model.SortType;
import io.driver.codrive.global.util.PageUtils;
import io.driver.codrive.modules.follow.domain.Follow;
import io.driver.codrive.modules.follow.domain.FollowRepository;
import io.driver.codrive.global.exception.AlreadyExistsApplicationException;
import io.driver.codrive.global.exception.IllegalArgumentApplicationException;
import io.driver.codrive.global.exception.NotFoundApplcationException;
import io.driver.codrive.global.exception.NotFoundApplicationException;
import io.driver.codrive.global.util.AuthUtils;
import io.driver.codrive.modules.follow.model.response.FollowingSummaryListResponse;
import io.driver.codrive.modules.follow.model.response.FollowingWeeklyCountResponse;
Expand Down Expand Up @@ -54,16 +56,22 @@ public void follow(String nickname) {
throw new IllegalArgumentApplicationException("자기 자신을 팔로우할 수 없습니다.");
}

if (getFollowByUsers(target, currentUser) != null) {
if (followRepository.existsByFollowingAndFollower(target, currentUser)) {
throw new AlreadyExistsApplicationException("팔로우 데이터");
}

Follow follow = Follow.toFollow(target, currentUser);
currentUser.addFollowing(follow);
target.addFollower(follow);
followRepository.save(follow);

notificationService.sendNotification(target, currentUser.getUserId(), NotificationType.FOLLOW, currentUser.getNickname());
try {
followRepository.save(follow);
currentUser.addFollowing(follow);
target.addFollower(follow);
} catch (DataIntegrityViolationException e) {
throw new InternalServerErrorApplicationException("팔로우할 수 없습니다.");
}

notificationService.sendNotification(target, currentUser.getUserId(), NotificationType.FOLLOW,
currentUser.getNickname());
}

@Transactional
Expand All @@ -73,7 +81,7 @@ public void cancelFollow(String nickname) {

Follow follow = getFollowByUsers(target, currentUser);
if (follow == null) {
throw new NotFoundApplcationException("팔로우 데이터");
throw new NotFoundApplicationException("팔로우 데이터");
}
followRepository.delete(follow);
target.deleteFollower(follow);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import org.springframework.transaction.annotation.Transactional;

import io.driver.codrive.global.exception.IllegalArgumentApplicationException;
import io.driver.codrive.global.exception.NotFoundApplcationException;
import io.driver.codrive.global.exception.NotFoundApplicationException;
import io.driver.codrive.global.model.SortType;
import io.driver.codrive.modules.mappings.roomUserMapping.domain.RoomUserMapping;
import io.driver.codrive.modules.mappings.roomUserMapping.domain.RoomUserMappingRepository;
Expand Down Expand Up @@ -44,7 +44,7 @@ public RoomUserMapping getRoomUserMapping(Room room, User user) {
public void deleteRoomUserMapping(Room room, User user) {
RoomUserMapping mapping = getRoomUserMapping(room, user);
if (mapping == null) {
throw new NotFoundApplcationException("멤버");
throw new NotFoundApplicationException("멤버");
}
room.deleteMember(mapping);
user.deleteJoinedRoom(mapping);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import io.driver.codrive.modules.codeblock.domain.Codeblock;
import io.driver.codrive.modules.codeblock.model.request.CodeblockModifyRequest;
import io.driver.codrive.modules.codeblock.service.CodeblockService;
import io.driver.codrive.global.exception.NotFoundApplcationException;
import io.driver.codrive.global.exception.NotFoundApplicationException;
import io.driver.codrive.global.util.AuthUtils;
import io.driver.codrive.modules.mappings.recordCategoryMapping.service.RecordCategoryMappingService;
import io.driver.codrive.modules.record.domain.Record;
Expand All @@ -42,7 +42,7 @@ public class RecordService {

@Transactional(readOnly = true)
public Record getRecordById(Long recordId) {
return recordRepository.findById(recordId).orElseThrow(() -> new NotFoundApplcationException("문제 풀이 데이터"));
return recordRepository.findById(recordId).orElseThrow(() -> new NotFoundApplicationException("문제 풀이 데이터"));
}

@Transactional(readOnly = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,12 @@ public String getPath(Record record, Long recordNum) {
return String.format(PATH, platformDirectoryName, levelDirectoryName, recordNum, title);
}

@Transactional
public String getContent(Record record) throws IOException {
String template = TemplateUtils.readTemplate(TEMPLATE_PATH);
Map<String, String> params = getContentMap(record);
return TemplateUtils.formatTemplate(template, params);
}

@Transactional
protected Map<String, String> getContentMap(Record record) {
Map<String, String> params = new HashMap<>();
params.put("title", record.getTitle());
Expand All @@ -97,14 +95,12 @@ protected Map<String, String> getContentMap(Record record) {
return params;
}

@Transactional
protected String getTags(List<String> categories) {
return categories.stream()
.map(category -> TAG_PREFIX + category)
.collect(Collectors.joining(TAG_DELIMITER));
}

@Transactional
protected String getCodeblocks(Record record) {
List<Codeblock> codeblocks = record.getCodeblocks();
String startBox = String.format(CODE_BOX_START, record.getUser().getLanguage().getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


import io.driver.codrive.global.exception.InternalServerErrorApplicationException;
import io.driver.codrive.global.exception.NotFoundApplcationException;
import io.driver.codrive.global.exception.NotFoundApplicationException;
import io.driver.codrive.global.exception.UnauthorizedApplicationException;
import io.driver.codrive.global.jwt.JwtProvider;
import io.driver.codrive.global.token.GithubToken;
Expand Down Expand Up @@ -75,7 +75,7 @@ public void saveGithubToken(Long userId, String accessToken, String response) {

public GithubToken getGithubTokenByUserId(Long userId) {
return githubTokenRepository.findById(String.valueOf(userId)).orElseThrow(
() -> new NotFoundApplcationException("Github Token")
() -> new NotFoundApplicationException("Github Token")
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import io.driver.codrive.global.discord.DiscordEventMessage;
import io.driver.codrive.global.discord.DiscordService;
import io.driver.codrive.global.exception.IllegalArgumentApplicationException;
import io.driver.codrive.global.exception.NotFoundApplcationException;
import io.driver.codrive.global.exception.NotFoundApplicationException;
import io.driver.codrive.global.util.AuthUtils;
import io.driver.codrive.global.util.MessageUtils;
import io.driver.codrive.global.util.PageUtils;
Expand Down Expand Up @@ -74,7 +74,7 @@ public RoomCreateResponse createRoom(RoomCreateRequest request, MultipartFile im

@Transactional
public Room getRoomById(Long roomId) {
return roomRepository.findById(roomId).orElseThrow(() -> new NotFoundApplcationException("그룹"));
return roomRepository.findById(roomId).orElseThrow(() -> new NotFoundApplicationException("그룹"));
}

@Transactional
Expand Down Expand Up @@ -107,7 +107,7 @@ public JoinedRoomInfoResponse getJoinedRoomInfo(Long roomId) {

@Transactional
public RoomUuidResponse getRoomInfoByUuid(String uuid) {
Room room = roomRepository.findByUuid(uuid).orElseThrow(() -> new NotFoundApplcationException("그룹"));
Room room = roomRepository.findByUuid(uuid).orElseThrow(() -> new NotFoundApplicationException("그룹"));
return RoomUuidResponse.of(room);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import org.springframework.transaction.annotation.Transactional;

import io.driver.codrive.global.exception.IllegalArgumentApplicationException;
import io.driver.codrive.global.exception.NotFoundApplcationException;
import io.driver.codrive.global.exception.NotFoundApplicationException;
import io.driver.codrive.global.util.AuthUtils;
import io.driver.codrive.global.util.MessageUtils;
import io.driver.codrive.modules.mappings.roomUserMapping.service.RoomUserMappingService;
Expand Down Expand Up @@ -110,7 +110,7 @@ protected void saveRoomRequest(RoomRequest roomRequest, Room room) {
@Transactional
public RoomRequest getRoomRequestById(Long roomRequestId) {
return roomRequestRepository.findById(roomRequestId)
.orElseThrow(() -> new NotFoundApplcationException("참여 요청 데이터"));
.orElseThrow(() -> new NotFoundApplicationException("참여 요청 데이터"));
}

@Transactional
Expand Down Expand Up @@ -152,14 +152,14 @@ public void changeWaitingRoomRequestStatus(Room room, UserRequestStatus originSt

@Transactional
public void deleteRoomRequest(Room room, User user) {
RoomRequest roomRequest = roomRequestRepository.findByRoomAndUser(room, user).orElseThrow(() -> new NotFoundApplcationException("참여 요청 데이터"));
RoomRequest roomRequest = roomRequestRepository.findByRoomAndUser(room, user).orElseThrow(() -> new NotFoundApplicationException("참여 요청 데이터"));
roomRequestRepository.delete(roomRequest);
}

@Transactional(readOnly = true)
public Room getRoomById(Long roomId) {
return roomRepository.findById(roomId)
.orElseThrow(() -> new NotFoundApplcationException("그룹"));
.orElseThrow(() -> new NotFoundApplicationException("그룹"));
}

@Transactional(readOnly = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import io.driver.codrive.global.discord.DiscordEventMessage;
import io.driver.codrive.global.discord.DiscordService;
import io.driver.codrive.global.exception.AlreadyExistsApplicationException;
import io.driver.codrive.global.exception.NotFoundApplcationException;
import io.driver.codrive.global.exception.NotFoundApplicationException;
import io.driver.codrive.global.util.AuthUtils;
import io.driver.codrive.modules.follow.domain.Follow;
import io.driver.codrive.modules.language.service.LanguageService;
Expand All @@ -35,12 +35,12 @@ public class UserService {

public User getUserById(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new NotFoundApplcationException("사용자"));
.orElseThrow(() -> new NotFoundApplicationException("사용자"));
}

public User getUserByNickname(String nickname) {
return userRepository.findByNickname(nickname)
.orElseThrow(() -> new NotFoundApplcationException("사용자"));
.orElseThrow(() -> new NotFoundApplicationException("사용자"));
}

public UserDetailResponse getUserInfo(Long userId) {
Expand All @@ -67,7 +67,7 @@ public void checkGithubRepositoryName(GithubRepositoryNameRequest request) {
User user = getUserById(AuthUtils.getCurrentUserId());
boolean isExistRepository = githubCommitService.isExistRepository(user, request.githubRepositoryName());
if (!isExistRepository) {
throw new NotFoundApplcationException("레포지토리");
throw new NotFoundApplicationException("레포지토리");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import org.springframework.test.util.ReflectionTestUtils;

import io.driver.codrive.global.exception.IllegalArgumentApplicationException;
import io.driver.codrive.global.exception.NotFoundApplcationException;
import io.driver.codrive.global.exception.NotFoundApplicationException;
import io.driver.codrive.global.util.DateUtils;
import io.driver.codrive.modules.codeblock.service.CodeblockService;
import io.driver.codrive.modules.language.domain.Language;
Expand Down Expand Up @@ -125,7 +125,7 @@ void getRecordById_faile_notFoundException() {
when(recordRepository.findById(recordId)).thenReturn(Optional.empty());

//when & then
assertThrows(NotFoundApplcationException.class, () -> recordService.getRecordById(recordId));
assertThrows(NotFoundApplicationException.class, () -> recordService.getRecordById(recordId));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import io.driver.codrive.global.exception.AlreadyExistsApplicationException;
import io.driver.codrive.global.exception.ForbiddenApplcationException;
import io.driver.codrive.global.exception.IllegalArgumentApplicationException;
import io.driver.codrive.global.exception.NotFoundApplcationException;
import io.driver.codrive.global.exception.NotFoundApplicationException;
import io.driver.codrive.modules.follow.domain.Follow;
import io.driver.codrive.modules.language.domain.Language;
import io.driver.codrive.modules.language.service.LanguageService;
Expand Down Expand Up @@ -156,7 +156,7 @@ void getUserById_fail_notFoundException() {
when(userRepository.findById(userId)).thenReturn(Optional.empty());

//when & then
assertThrows(NotFoundApplcationException.class, () -> userService.getUserById(userId));
assertThrows(NotFoundApplicationException.class, () -> userService.getUserById(userId));
}

@Test
Expand All @@ -181,9 +181,9 @@ void getUserByNickname_fail_notFound() {
when(userRepository.findByNickname(nickname)).thenReturn(Optional.empty());

//when & then
NotFoundApplcationException notFoundApplcationException = assertThrows(NotFoundApplcationException.class,
NotFoundApplicationException notFoundApplicationException = assertThrows(NotFoundApplicationException.class,
() -> userService.getUserByNickname(nickname));
assertEquals("사용자을/를 찾을 수 없습니다.", notFoundApplcationException.getMessage());
assertEquals("사용자을/를 찾을 수 없습니다.", notFoundApplicationException.getMessage());
}

@Test
Expand All @@ -208,7 +208,7 @@ void getUserInfo_fail_notFound() {
when(userRepository.findById(userId)).thenReturn(Optional.empty());

//when & then
assertThrows(NotFoundApplcationException.class, () -> userService.getUserInfo(userId));
assertThrows(NotFoundApplicationException.class, () -> userService.getUserInfo(userId));
}

@Test
Expand All @@ -225,7 +225,6 @@ void getProfile_success_follow() {
Follow follow = Follow.builder() //현재 로그인한 유저(mockUser) -> 다른 유저(mockOtherUser) 팔로우
.following(mockOtherUser)
.follower(mockUser)
.canceled(false)
.build();
mockUser.addFollowing(follow);

Expand Down Expand Up @@ -348,7 +347,7 @@ void checkGithubRepositoryName_fail() {

//when & then
GithubRepositoryNameRequest request = new GithubRepositoryNameRequest("REPOSITORY_NAME");
assertThrows(NotFoundApplcationException.class, () -> userService.checkGithubRepositoryName(request));
assertThrows(NotFoundApplicationException.class, () -> userService.checkGithubRepositoryName(request));

tearDown();
}
Expand Down Expand Up @@ -441,7 +440,6 @@ void getFollowings_success() {
Follow follow = Follow.builder() //현재 로그인한 유저(mockUser) -> 다른 유저(mockOtherUser) 팔로우
.following(mockOtherUser)
.follower(mockUser)
.canceled(false)
.build();
mockUser.addFollowing(follow);

Expand Down Expand Up @@ -477,7 +475,6 @@ void getFollowers_success_not_following() {
Follow follow = Follow.builder() //다른 유저(mockOtherUser) -> 현재 로그인한 유저(mockUser) 팔로우
.following(mockUser)
.follower(mockOtherUser)
.canceled(false)
.build();
mockUser.addFollower(follow);

Expand Down

0 comments on commit e2a4e46

Please sign in to comment.