diff --git a/src/main/java/site/katchup/katchupserver/api/auth/service/GoogleAuthService.java b/src/main/java/site/katchup/katchupserver/api/auth/service/GoogleAuthService.java index 3b6d9c0..dccdf19 100644 --- a/src/main/java/site/katchup/katchupserver/api/auth/service/GoogleAuthService.java +++ b/src/main/java/site/katchup/katchupserver/api/auth/service/GoogleAuthService.java @@ -13,7 +13,7 @@ import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import site.katchup.katchupserver.api.auth.dto.GoogleInfoDto; -import site.katchup.katchupserver.common.exception.CustomException; +import site.katchup.katchupserver.common.exception.UnauthorizedException; import site.katchup.katchupserver.common.response.ErrorStatus; @RequiredArgsConstructor @@ -48,7 +48,7 @@ public static GoogleInfoDto getGoogleData(String googleToken) { return new GoogleInfoDto(nickname, email, imageUrl); } catch (HttpClientErrorException e) { - throw new CustomException(ErrorStatus.GOOGLE_UNAUTHORIZED_USER); + throw new UnauthorizedException(ErrorStatus.GOOGLE_UNAUTHORIZED_USER); } catch (JsonProcessingException e) { throw new RuntimeException(e); } diff --git a/src/main/java/site/katchup/katchupserver/api/auth/service/Impl/AuthServiceImpl.java b/src/main/java/site/katchup/katchupserver/api/auth/service/Impl/AuthServiceImpl.java index 6e7a0cb..33016dd 100644 --- a/src/main/java/site/katchup/katchupserver/api/auth/service/Impl/AuthServiceImpl.java +++ b/src/main/java/site/katchup/katchupserver/api/auth/service/Impl/AuthServiceImpl.java @@ -12,7 +12,7 @@ import site.katchup.katchupserver.api.auth.service.GoogleAuthService; import site.katchup.katchupserver.api.member.domain.Member; import site.katchup.katchupserver.api.member.repository.MemberRepository; -import site.katchup.katchupserver.common.exception.CustomException; +import site.katchup.katchupserver.common.exception.UnauthorizedException; import site.katchup.katchupserver.common.response.ErrorStatus; import site.katchup.katchupserver.config.jwt.JwtTokenProvider; import site.katchup.katchupserver.config.jwt.UserAuthentication; @@ -77,7 +77,7 @@ public AuthTokenGetResponseDto getNewToken(String accessToken, String refreshTok private Member findMemberByEmail(String email) { return memberRepository.findByEmail(email) - .orElseThrow(() -> new CustomException(ErrorStatus.INVALID_MEMBER)); + .orElseThrow(() -> new UnauthorizedException(ErrorStatus.INVALID_MEMBER)); } private boolean isMemberByEmail(String email) { diff --git a/src/main/java/site/katchup/katchupserver/api/card/service/Impl/CardServiceImpl.java b/src/main/java/site/katchup/katchupserver/api/card/service/Impl/CardServiceImpl.java index 6b3925e..6c8e0c2 100644 --- a/src/main/java/site/katchup/katchupserver/api/card/service/Impl/CardServiceImpl.java +++ b/src/main/java/site/katchup/katchupserver/api/card/service/Impl/CardServiceImpl.java @@ -28,8 +28,8 @@ import site.katchup.katchupserver.api.task.repository.TaskRepository; import site.katchup.katchupserver.api.trash.domain.Trash; import site.katchup.katchupserver.api.trash.repository.TrashRepository; -import site.katchup.katchupserver.common.exception.CustomException; -import site.katchup.katchupserver.common.exception.EntityNotFoundException; +import site.katchup.katchupserver.common.exception.BadRequestException; +import site.katchup.katchupserver.common.exception.NotFoundException; import site.katchup.katchupserver.common.response.ErrorStatus; import site.katchup.katchupserver.common.util.S3Util; @@ -122,7 +122,7 @@ public void createCard(List fileList, CardCreateRequestDto reques .build()); } } catch (IOException e) { - throw new CustomException(ErrorStatus.FILE_UPLOAD_ERROR); + throw new BadRequestException(ErrorStatus.FILE_UPLOAD_ERROR); } } @@ -174,7 +174,7 @@ private ObjectMetadata getObjectMetadata(MultipartFile file) { private void validateFileSize(MultipartFile file) { if (file.getSize() >= MAX_FILE_SIZE) { - throw new CustomException(ErrorStatus.FILE_SIZE_EXCEED); + throw new BadRequestException(ErrorStatus.FILE_SIZE_EXCEED); } } @@ -198,34 +198,34 @@ private List getFileDtoList(Long cardId) { private Card getCardById(Long cardId) { Card card = cardRepository.findById(cardId).orElseThrow( - () -> new EntityNotFoundException(ErrorStatus.NOT_FOUND_CARD) + () -> new NotFoundException(ErrorStatus.NOT_FOUND_CARD) ); if (card.isDeleted()) { - throw new CustomException(ErrorStatus.DELETED_CARD); + throw new NotFoundException(ErrorStatus.DELETED_CARD); } return card; } private Folder getFolderById(Long folderId) { return folderRepository.findById(folderId).orElseThrow( - () -> new EntityNotFoundException(ErrorStatus.NOT_FOUND_FOLDER)); + () -> new NotFoundException(ErrorStatus.NOT_FOUND_FOLDER)); } private Category getCategoryById(Long categoryId) { return categoryRepository.findById(categoryId).orElseThrow( - () -> new EntityNotFoundException(ErrorStatus.NOT_FOUND_CATEGORY)); + () -> new NotFoundException(ErrorStatus.NOT_FOUND_CATEGORY)); } private void validatePdf(MultipartFile file) { if (!file.getContentType().equals(PDF_TYPE)) { - throw new CustomException(ErrorStatus.NOT_PDF_FILE_TYPE); + throw new BadRequestException(ErrorStatus.NOT_PDF_FILE_TYPE); } } private Task getTaskById(Long taskId) { return taskRepository.findById(taskId).orElseThrow( - () -> new EntityNotFoundException(ErrorStatus.INVALID_TASK)); + () -> new NotFoundException(ErrorStatus.INVALID_TASK)); } diff --git a/src/main/java/site/katchup/katchupserver/api/category/service/Impl/CategoryServiceImpl.java b/src/main/java/site/katchup/katchupserver/api/category/service/Impl/CategoryServiceImpl.java index e3bb12a..32aa5cb 100644 --- a/src/main/java/site/katchup/katchupserver/api/category/service/Impl/CategoryServiceImpl.java +++ b/src/main/java/site/katchup/katchupserver/api/category/service/Impl/CategoryServiceImpl.java @@ -16,7 +16,8 @@ import site.katchup.katchupserver.api.member.repository.MemberRepository; import site.katchup.katchupserver.api.task.domain.Task; import site.katchup.katchupserver.api.card.domain.Card; -import site.katchup.katchupserver.common.exception.CustomException; +import site.katchup.katchupserver.common.exception.BadRequestException; +import site.katchup.katchupserver.common.exception.UnauthorizedException; import site.katchup.katchupserver.common.response.ErrorStatus; import java.util.List; @@ -36,7 +37,7 @@ public class CategoryServiceImpl implements CategoryService { @Transactional public void createCategoryName(Long memberId, CategoryCreateRequestDto requestDto) { if (checkDuplicateCategoryName(memberId, requestDto.getName())) { - throw new CustomException(ErrorStatus.DUPLICATE_CATEGORY_NAME); + throw new BadRequestException(ErrorStatus.DUPLICATE_CATEGORY_NAME); } categoryRepository.save(Category.builder() @@ -61,7 +62,7 @@ public void updateCategoryName(Long memberId, Long categoryId, CategoryUpdateReq .orElseThrow(() -> new EntityNotFoundException(NOT_FOUND_CATEGORY.getMessage())); if (checkDuplicateCategoryName(memberId, requestDto.getName())) { - throw new CustomException(ErrorStatus.DUPLICATE_FOLDER_NAME); + throw new BadRequestException(ErrorStatus.DUPLICATE_FOLDER_NAME); } findCategory.updateCategoryName(requestDto.getName()); @@ -94,6 +95,6 @@ private void deleteFolderAndTaskAndCard(Folder folder) { private Member findMember(Long memberId) { return memberRepository.findById(memberId) - .orElseThrow(() -> new CustomException(ErrorStatus.INVALID_MEMBER)); + .orElseThrow(() -> new UnauthorizedException(ErrorStatus.INVALID_MEMBER)); } } \ No newline at end of file diff --git a/src/main/java/site/katchup/katchupserver/api/common/CardProvider.java b/src/main/java/site/katchup/katchupserver/api/common/CardProvider.java index bbc00e4..c248608 100644 --- a/src/main/java/site/katchup/katchupserver/api/common/CardProvider.java +++ b/src/main/java/site/katchup/katchupserver/api/common/CardProvider.java @@ -1,10 +1,10 @@ package site.katchup.katchupserver.api.common; -import jakarta.persistence.EntityNotFoundException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import site.katchup.katchupserver.api.card.domain.Card; import site.katchup.katchupserver.api.card.repository.CardRepository; +import site.katchup.katchupserver.common.exception.NotFoundException; import site.katchup.katchupserver.common.response.ErrorStatus; @Service @@ -14,6 +14,6 @@ public class CardProvider { private final CardRepository cardRepository; public Card getCardById(Long cardId) { - return cardRepository.findById(cardId).orElseThrow(() -> new EntityNotFoundException(ErrorStatus.NOT_FOUND_CARD.getMessage())); + return cardRepository.findById(cardId).orElseThrow(() -> new NotFoundException(ErrorStatus.NOT_FOUND_CARD)); } } diff --git a/src/main/java/site/katchup/katchupserver/api/folder/service/Impl/FolderServiceImpl.java b/src/main/java/site/katchup/katchupserver/api/folder/service/Impl/FolderServiceImpl.java index 2703baa..c5e1085 100644 --- a/src/main/java/site/katchup/katchupserver/api/folder/service/Impl/FolderServiceImpl.java +++ b/src/main/java/site/katchup/katchupserver/api/folder/service/Impl/FolderServiceImpl.java @@ -13,8 +13,8 @@ import site.katchup.katchupserver.api.folder.repository.FolderRepository; import site.katchup.katchupserver.api.folder.service.FolderService; import site.katchup.katchupserver.api.task.domain.Task; -import site.katchup.katchupserver.common.exception.CustomException; -import site.katchup.katchupserver.common.exception.EntityNotFoundException; +import site.katchup.katchupserver.common.exception.BadRequestException; +import site.katchup.katchupserver.common.exception.NotFoundException; import site.katchup.katchupserver.common.response.ErrorStatus; import java.util.List; @@ -51,10 +51,10 @@ public List getByCategoryId(Long categoryId) { @Transactional public void updateFolderName(Long folderId, FolderUpdateRequestDto requestDto) { Folder findFolder = folderRepository.findById(folderId) - .orElseThrow(() -> new EntityNotFoundException(NOT_FOUND_FOLDER)); + .orElseThrow(() -> new NotFoundException(NOT_FOUND_FOLDER)); if (checkDuplicateFolderName(findFolder.getCategory().getId(), requestDto.getName())) { - throw new CustomException(ErrorStatus.DUPLICATE_FOLDER_NAME); + throw new BadRequestException(ErrorStatus.DUPLICATE_FOLDER_NAME); } findFolder.updateFolderName(requestDto.getName()); @@ -64,9 +64,9 @@ public void updateFolderName(Long folderId, FolderUpdateRequestDto requestDto) { @Transactional public void createFolderName(FolderCreateRequestDto requestDto) { Category category = categoryRepository.findById(requestDto.getCategoryId()) - .orElseThrow(() -> new EntityNotFoundException(NOT_FOUND_CATEGORY)); + .orElseThrow(() -> new NotFoundException(NOT_FOUND_CATEGORY)); if (checkDuplicateFolderName(requestDto.getCategoryId(), requestDto.getName())) { - throw new CustomException(ErrorStatus.DUPLICATE_FOLDER_NAME); + throw new BadRequestException(ErrorStatus.DUPLICATE_FOLDER_NAME); } folderRepository.save(Folder.builder() @@ -94,6 +94,6 @@ private void deleteTaskAndCard(Task task) { private Folder getFolderById(Long folderId) { return folderRepository.findById(folderId) - .orElseThrow(() -> new EntityNotFoundException(NOT_FOUND_FOLDER)); + .orElseThrow(() -> new NotFoundException(NOT_FOUND_FOLDER)); } } diff --git a/src/main/java/site/katchup/katchupserver/api/member/service/Impl/MemberServiceImpl.java b/src/main/java/site/katchup/katchupserver/api/member/service/Impl/MemberServiceImpl.java index ada36c8..0655e6c 100644 --- a/src/main/java/site/katchup/katchupserver/api/member/service/Impl/MemberServiceImpl.java +++ b/src/main/java/site/katchup/katchupserver/api/member/service/Impl/MemberServiceImpl.java @@ -7,7 +7,7 @@ import site.katchup.katchupserver.api.member.dto.MemberProfileGetResponseDto; import site.katchup.katchupserver.api.member.repository.MemberRepository; import site.katchup.katchupserver.api.member.service.MemberService; -import site.katchup.katchupserver.common.exception.CustomException; +import site.katchup.katchupserver.common.exception.UnauthorizedException; import site.katchup.katchupserver.common.response.ErrorStatus; @Service @@ -25,6 +25,6 @@ public MemberProfileGetResponseDto getMemberProfile(Long memberId) { private Member findMember(Long memberId) { return memberRepository.findById(memberId) - .orElseThrow(() -> new CustomException(ErrorStatus.INVALID_MEMBER)); + .orElseThrow(() -> new UnauthorizedException(ErrorStatus.INVALID_MEMBER)); } } diff --git a/src/main/java/site/katchup/katchupserver/api/screenshot/service/impl/ScreenshotServiceImpl.java b/src/main/java/site/katchup/katchupserver/api/screenshot/service/impl/ScreenshotServiceImpl.java index 50ab73e..7a41dd9 100644 --- a/src/main/java/site/katchup/katchupserver/api/screenshot/service/impl/ScreenshotServiceImpl.java +++ b/src/main/java/site/katchup/katchupserver/api/screenshot/service/impl/ScreenshotServiceImpl.java @@ -12,7 +12,7 @@ import site.katchup.katchupserver.api.screenshot.repository.ScreenshotRepository; import site.katchup.katchupserver.api.screenshot.service.ScreenshotService; import site.katchup.katchupserver.api.screenshot.service.ScreenshotValidator; -import site.katchup.katchupserver.common.exception.CustomException; +import site.katchup.katchupserver.common.exception.InternalServerException; import site.katchup.katchupserver.common.response.ErrorStatus; import site.katchup.katchupserver.common.util.S3Util; @@ -63,7 +63,7 @@ public ScreenshotUploadResponseDto uploadScreenshot(MultipartFile file, Long car .build(); } catch (Exception e) { - throw new CustomException(ErrorStatus.IMAGE_UPLOAD_EXCEPTION); + throw new InternalServerException(ErrorStatus.IMAGE_UPLOAD_EXCEPTION); } } @@ -99,7 +99,7 @@ private String extractExtension(MultipartFile file) { try { return file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); } catch (StringIndexOutOfBoundsException e) { - throw new CustomException(ErrorStatus.IMAGE_UPLOAD_EXCEPTION); + throw new InternalServerException(ErrorStatus.IMAGE_UPLOAD_EXCEPTION); } } } diff --git a/src/main/java/site/katchup/katchupserver/api/task/service/Impl/TaskServiceImpl.java b/src/main/java/site/katchup/katchupserver/api/task/service/Impl/TaskServiceImpl.java index 93cf96b..76d442b 100644 --- a/src/main/java/site/katchup/katchupserver/api/task/service/Impl/TaskServiceImpl.java +++ b/src/main/java/site/katchup/katchupserver/api/task/service/Impl/TaskServiceImpl.java @@ -10,7 +10,7 @@ import site.katchup.katchupserver.api.task.dto.response.TaskGetResponseDto; import site.katchup.katchupserver.api.task.repository.TaskRepository; import site.katchup.katchupserver.api.task.service.TaskService; -import site.katchup.katchupserver.common.exception.CustomException; +import site.katchup.katchupserver.common.exception.NotFoundException; import site.katchup.katchupserver.common.response.ErrorStatus; import java.util.List; @@ -37,7 +37,7 @@ public List getAllTask(Long memberId) { @Override public void createTask(TaskCreateRequestDto requestDto) { Folder folder = folderRepository.findById(requestDto.getFolderId()) - .orElseThrow(() -> new CustomException(ErrorStatus.NOT_FOUND_FOLDER)); + .orElseThrow(() -> new NotFoundException(ErrorStatus.NOT_FOUND_FOLDER)); Task task = new Task(requestDto.getName(), folder); diff --git a/src/main/java/site/katchup/katchupserver/common/advice/ControllerExceptionAdvice.java b/src/main/java/site/katchup/katchupserver/common/advice/ControllerExceptionAdvice.java index fc2275a..8e42568 100644 --- a/src/main/java/site/katchup/katchupserver/common/advice/ControllerExceptionAdvice.java +++ b/src/main/java/site/katchup/katchupserver/common/advice/ControllerExceptionAdvice.java @@ -2,60 +2,37 @@ import jakarta.persistence.EntityNotFoundException; import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import site.katchup.katchupserver.common.dto.ApiResponseDto; -import site.katchup.katchupserver.common.exception.CustomException; +import site.katchup.katchupserver.common.exception.BaseException; import site.katchup.katchupserver.common.response.ErrorStatus; -import java.util.List; -import java.util.stream.Collectors; @RestControllerAdvice public class ControllerExceptionAdvice { - /** - * CustomException - */ - @ExceptionHandler(CustomException.class) - protected ApiResponseDto handleCustomException(final CustomException e) { - return ApiResponseDto.error(e.getErrorStatus()); + @ExceptionHandler(BaseException.class) + public ResponseEntity handleGlobalException(BaseException ex) { + return ResponseEntity.status(ex.getStatusCode()) + .body(ApiResponseDto.error(ex.getStatusCode().value(), ex.getResponseMessage())); } - /** - * EntityNotFoundException - */ - @ExceptionHandler(EntityNotFoundException.class) - protected ApiResponseDto handleEntityNotFoundException(final EntityNotFoundException e) { - return ApiResponseDto.error(ErrorStatus.valueOf(e.getMessage())); + @ExceptionHandler(MissingServletRequestParameterException.class) + public ResponseEntity handleMissingParameter(MissingServletRequestParameterException ex) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(ApiResponseDto.error(HttpStatus.BAD_REQUEST.value(), + ErrorStatus.VALIDATION_REQUEST_MISSING_EXCEPTION.getMessage())); } - /** - * 400 BAD_REQUEST - */ - @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler(MethodArgumentNotValidException.class) - protected ApiResponseDto handleMethodArgumentNotValidException(final MethodArgumentNotValidException e) { - String errorMessage = e.getFieldError().getDefaultMessage(); - if (errorMessage.equals(ErrorStatus.VALIDATION_NAMING_EXCEPTION.getMessage())) - return ApiResponseDto.error(ErrorStatus.VALIDATION_NAMING_EXCEPTION); - return ApiResponseDto.error(ErrorStatus.VALIDATION_EXCEPTION); - } - - @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(IllegalArgumentException.class) - protected ApiResponseDto handleIllegalArgumentException(IllegalArgumentException e ) { - return ApiResponseDto.error(ErrorStatus.valueOf(e.getMessage())); + public ResponseEntity handleIllegalArgument(IllegalArgumentException ex) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(ApiResponseDto.error(HttpStatus.BAD_REQUEST.value(), ex.getMessage())); } - /** - * 500 INTERNAL_SERVER_ERROR - */ - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - @ExceptionHandler(Exception.class) - public ApiResponseDto unhandledExceptionHandler(final Exception e) { - return ApiResponseDto.error(ErrorStatus.INTERNAL_SERVER_ERROR); - } } diff --git a/src/main/java/site/katchup/katchupserver/common/dto/ApiResponseDto.java b/src/main/java/site/katchup/katchupserver/common/dto/ApiResponseDto.java index 47bb10c..b0f3cb6 100644 --- a/src/main/java/site/katchup/katchupserver/common/dto/ApiResponseDto.java +++ b/src/main/java/site/katchup/katchupserver/common/dto/ApiResponseDto.java @@ -14,6 +14,15 @@ public class ApiResponseDto { private final String message; private T data; + public static ApiResponseDto success(SuccessStatus status, Object data) { + return ApiResponseDto.builder() + .status(status.getHttpStatus().value()) + .success(true) + .message(status.getMessage()) + .data(data) + .build(); + } + public static ApiResponseDto success(SuccessStatus successStatus) { return ApiResponseDto.builder() .status(successStatus.getHttpStatus().value()) @@ -22,12 +31,12 @@ public static ApiResponseDto success(SuccessStatus successStatus) { .build(); } - public static ApiResponseDto success(SuccessStatus successStatus, T data) { - return new ApiResponseDto(successStatus.getHttpStatus().value(), true, successStatus.getMessage(), data); - } - - public static ApiResponseDto error(ErrorStatus errorStatus) { - return new ApiResponseDto<>(errorStatus.getHttpStatus().value(), false, errorStatus.getMessage()); + public static ApiResponseDto error(int status, String message) { + return ApiResponseDto.builder() + .status(status) + .success(false) + .message(message) + .build(); } } diff --git a/src/main/java/site/katchup/katchupserver/common/exception/BadRequestException.java b/src/main/java/site/katchup/katchupserver/common/exception/BadRequestException.java new file mode 100644 index 0000000..29aa271 --- /dev/null +++ b/src/main/java/site/katchup/katchupserver/common/exception/BadRequestException.java @@ -0,0 +1,16 @@ +package site.katchup.katchupserver.common.exception; + +import org.springframework.http.HttpStatus; +import site.katchup.katchupserver.common.response.ErrorStatus; + +public class BadRequestException extends BaseException { + + public BadRequestException(ErrorStatus errorStatus) { + super(HttpStatus.BAD_REQUEST, errorStatus.getMessage()); + } + + public BadRequestException(String message) { + super(HttpStatus.BAD_REQUEST, message); + } + +} diff --git a/src/main/java/site/katchup/katchupserver/common/exception/BaseException.java b/src/main/java/site/katchup/katchupserver/common/exception/BaseException.java new file mode 100644 index 0000000..bd8a31c --- /dev/null +++ b/src/main/java/site/katchup/katchupserver/common/exception/BaseException.java @@ -0,0 +1,25 @@ +package site.katchup.katchupserver.common.exception; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.http.HttpStatus; +import site.katchup.katchupserver.common.response.ErrorStatus; + +@Getter +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class BaseException extends RuntimeException { + HttpStatus statusCode; + String responseMessage; + + public BaseException(HttpStatus statusCode) { + super(); + this.statusCode = statusCode; + } + + public BaseException(HttpStatus statusCode, String responseMessage) { + super(responseMessage); + this.statusCode = statusCode; + this.responseMessage = responseMessage; + } +} diff --git a/src/main/java/site/katchup/katchupserver/common/exception/CustomException.java b/src/main/java/site/katchup/katchupserver/common/exception/CustomException.java deleted file mode 100644 index c8145e1..0000000 --- a/src/main/java/site/katchup/katchupserver/common/exception/CustomException.java +++ /dev/null @@ -1,14 +0,0 @@ -package site.katchup.katchupserver.common.exception; - -import lombok.Getter; -import site.katchup.katchupserver.common.response.ErrorStatus; - -@Getter -public class CustomException extends RuntimeException { - private final ErrorStatus errorStatus; - - public CustomException(ErrorStatus errorStatus) { - super(errorStatus.getMessage()); - this.errorStatus = errorStatus; - } -} diff --git a/src/main/java/site/katchup/katchupserver/common/exception/EntityNotFoundException.java b/src/main/java/site/katchup/katchupserver/common/exception/EntityNotFoundException.java deleted file mode 100644 index d88c987..0000000 --- a/src/main/java/site/katchup/katchupserver/common/exception/EntityNotFoundException.java +++ /dev/null @@ -1,14 +0,0 @@ -package site.katchup.katchupserver.common.exception; - -import lombok.Getter; -import site.katchup.katchupserver.common.response.ErrorStatus; - -@Getter -public class EntityNotFoundException extends RuntimeException { - private final ErrorStatus errorStatus; - - public EntityNotFoundException(ErrorStatus errorStatus) { - super(errorStatus.getMessage()); - this.errorStatus = errorStatus; - } -} diff --git a/src/main/java/site/katchup/katchupserver/common/exception/InternalServerException.java b/src/main/java/site/katchup/katchupserver/common/exception/InternalServerException.java new file mode 100644 index 0000000..15cbdb5 --- /dev/null +++ b/src/main/java/site/katchup/katchupserver/common/exception/InternalServerException.java @@ -0,0 +1,16 @@ +package site.katchup.katchupserver.common.exception; + +import org.springframework.http.HttpStatus; +import site.katchup.katchupserver.common.response.ErrorStatus; + +public class InternalServerException extends BaseException { + + public InternalServerException(ErrorStatus errorStatus) { + super(HttpStatus.INTERNAL_SERVER_ERROR, errorStatus.getMessage()); + } + + public InternalServerException(String message) { + super(HttpStatus.INTERNAL_SERVER_ERROR, message); + } + +} diff --git a/src/main/java/site/katchup/katchupserver/common/exception/NotFoundException.java b/src/main/java/site/katchup/katchupserver/common/exception/NotFoundException.java new file mode 100644 index 0000000..a9e5d2e --- /dev/null +++ b/src/main/java/site/katchup/katchupserver/common/exception/NotFoundException.java @@ -0,0 +1,16 @@ +package site.katchup.katchupserver.common.exception; + +import lombok.Getter; +import org.springframework.http.HttpStatus; +import site.katchup.katchupserver.common.response.ErrorStatus; + +@Getter +public class NotFoundException extends BaseException { + public NotFoundException(ErrorStatus errorStatus) { + super(HttpStatus.NOT_FOUND, errorStatus.getMessage()); + } + + public NotFoundException(String message) { + super(HttpStatus.NOT_FOUND, message); + } +} diff --git a/src/main/java/site/katchup/katchupserver/common/exception/UnauthorizedException.java b/src/main/java/site/katchup/katchupserver/common/exception/UnauthorizedException.java new file mode 100644 index 0000000..58a0ba3 --- /dev/null +++ b/src/main/java/site/katchup/katchupserver/common/exception/UnauthorizedException.java @@ -0,0 +1,15 @@ +package site.katchup.katchupserver.common.exception; + +import org.springframework.http.HttpStatus; +import site.katchup.katchupserver.common.response.ErrorStatus; + +public class UnauthorizedException extends BaseException { + + public UnauthorizedException(ErrorStatus errorStatus) { + super(HttpStatus.UNAUTHORIZED, errorStatus.getMessage()); + } + + public UnauthorizedException(String message) { + super(HttpStatus.UNAUTHORIZED, message); + } +} diff --git a/src/main/java/site/katchup/katchupserver/common/response/ErrorStatus.java b/src/main/java/site/katchup/katchupserver/common/response/ErrorStatus.java index 157e012..696d3ad 100644 --- a/src/main/java/site/katchup/katchupserver/common/response/ErrorStatus.java +++ b/src/main/java/site/katchup/katchupserver/common/response/ErrorStatus.java @@ -11,43 +11,40 @@ public enum ErrorStatus { /** * 400 BAD_REQUEST */ - VALIDATION_EXCEPTION(HttpStatus.BAD_REQUEST, "잘못된 요청입니다."), - VALIDATION_REQUEST_MISSING_EXCEPTION(HttpStatus.BAD_REQUEST, "요청값이 입력되지 않았습니다."), - VALIDATION_NAMING_EXCEPTION(HttpStatus.BAD_REQUEST, "이모지 및 특수기호 입력은 불가능합니다. 제외하여 입력해 주세요."), - NO_TOKEN(HttpStatus.BAD_REQUEST, "토큰을 넣어주세요."), - DUPLICATE_FOLDER_NAME(HttpStatus.BAD_REQUEST, "해당 중분류명은 이미 존재합니다. 다른 업무명을 입력해 주세요."), - DUPLICATE_CATEGORY_NAME(HttpStatus.BAD_REQUEST, "해당 대분류명은 이미 존재합니다. 다른 업무명을 입력해 주세요."), - NOT_PDF_FILE_TYPE(HttpStatus.BAD_REQUEST, "PDF 파일만 업로드 가능합니다."), - FILE_UPLOAD_ERROR(HttpStatus.BAD_REQUEST, "파일 업로드를 실패했습니다."), - FILE_SIZE_EXCEED(HttpStatus.BAD_REQUEST, "파일 사이즈가 10MB를 초과했습니다."), - INVALID_TASK(HttpStatus.BAD_REQUEST, "존재하지 않는 업무입니다."), + VALIDATION_EXCEPTION("잘못된 요청입니다."), + VALIDATION_REQUEST_MISSING_EXCEPTION("요청값이 입력되지 않았습니다."), + VALIDATION_NAMING_EXCEPTION("이모지 및 특수기호 입력은 불가능합니다. 제외하여 입력해 주세요."), + NO_TOKEN("토큰을 넣어주세요."), + DUPLICATE_FOLDER_NAME("해당 중분류명은 이미 존재합니다. 다른 업무명을 입력해 주세요."), + DUPLICATE_CATEGORY_NAME("해당 대분류명은 이미 존재합니다. 다른 업무명을 입력해 주세요."), + NOT_PDF_FILE_TYPE("PDF 파일만 업로드 가능합니다."), + FILE_UPLOAD_ERROR("파일 업로드를 실패했습니다."), + FILE_SIZE_EXCEED("파일 사이즈가 10MB를 초과했습니다."), /** * 401 UNAUTHORIZED */ - UNAUTHORIZED_TOKEN(HttpStatus.UNAUTHORIZED, "유효하지 않은 토큰입니다."), - INVALID_MEMBER(HttpStatus.UNAUTHORIZED, "유효하지 않은 유저입니다."), - GOOGLE_UNAUTHORIZED_USER(HttpStatus.UNAUTHORIZED, "구글 로그인 실패. 만료되었거나 잘못된 구글 토큰입니다."), - SIGNIN_REQUIRED(HttpStatus.UNAUTHORIZED, "access, refreshToken 모두 만료되었습니다. 재로그인이 필요합니다."), - VALID_ACCESS_TOKEN(HttpStatus.UNAUTHORIZED, "아직 유효한 accessToken 입니다."), + UNAUTHORIZED_TOKEN("유효하지 않은 토큰입니다."), + INVALID_MEMBER("유효하지 않은 유저입니다."), + GOOGLE_UNAUTHORIZED_USER("구글 로그인 실패. 만료되었거나 잘못된 구글 토큰입니다."), + SIGNIN_REQUIRED("access, refreshToken 모두 만료되었습니다. 재로그인이 필요합니다."), + VALID_ACCESS_TOKEN("아직 유효한 accessToken 입니다."), /** * 404 NOT_FOUND */ - NOT_FOUND_FOLDER(HttpStatus.NOT_FOUND, "존재하지 않는 중분류 폴더입니다."), - NOT_FOUND_CARD(HttpStatus.NOT_FOUND, "존재하지 않는 업무 카드입니다."), - NOT_FOUND_CATEGORY(HttpStatus.NOT_FOUND, "존재하지 않는 대분류 카테고리입니다."), - DELETED_CARD(HttpStatus.NOT_FOUND, "이미 삭제된 업무 카드입니다."), + NOT_FOUND_FOLDER("존재하지 않는 중분류 폴더입니다."), + NOT_FOUND_CARD("존재하지 않는 업무 카드입니다."), + NOT_FOUND_CATEGORY("존재하지 않는 대분류 카테고리입니다."), + DELETED_CARD("이미 삭제된 업무 카드입니다."), + INVALID_TASK("존재하지 않는 업무입니다."), /** * 500 SERVER_ERROR */ - INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "예상치 못한 서버 에러가 발생했습니다."), - BAD_GATEWAY_EXCEPTION(HttpStatus.BAD_GATEWAY, "일시적인 에러가 발생하였습니다.\n잠시 후 다시 시도해주세요!"), - SERVICE_UNAVAILABLE_EXCEPTION(HttpStatus.SERVICE_UNAVAILABLE, "현재 점검 중입니다.\n잠시 후 다시 시도해주세요!"), - IMAGE_UPLOAD_EXCEPTION(HttpStatus.INTERNAL_SERVER_ERROR, "이미지 업로드에 실패하였습니다."); - - private final HttpStatus httpStatus; + INTERNAL_SERVER_ERROR("예상치 못한 서버 에러가 발생했습니다."), + IMAGE_UPLOAD_EXCEPTION("이미지 업로드에 실패하였습니다."); + private final String message; } diff --git a/src/main/java/site/katchup/katchupserver/common/util/MemberUtil.java b/src/main/java/site/katchup/katchupserver/common/util/MemberUtil.java index a38a711..5468b47 100644 --- a/src/main/java/site/katchup/katchupserver/common/util/MemberUtil.java +++ b/src/main/java/site/katchup/katchupserver/common/util/MemberUtil.java @@ -2,7 +2,7 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; -import site.katchup.katchupserver.common.exception.CustomException; +import site.katchup.katchupserver.common.exception.UnauthorizedException; import site.katchup.katchupserver.common.response.ErrorStatus; import java.security.Principal; @@ -11,7 +11,7 @@ public class MemberUtil { public static Long getMemberId(Principal principal) { if (principal == null) { - throw new CustomException(ErrorStatus.INVALID_MEMBER); + throw new UnauthorizedException(ErrorStatus.INVALID_MEMBER); } return Long.valueOf(principal.getName()); } diff --git a/src/main/java/site/katchup/katchupserver/config/jwt/JwtAuthenticationEntryPoint.java b/src/main/java/site/katchup/katchupserver/config/jwt/JwtAuthenticationEntryPoint.java index 2f6a96f..bc02216 100644 --- a/src/main/java/site/katchup/katchupserver/config/jwt/JwtAuthenticationEntryPoint.java +++ b/src/main/java/site/katchup/katchupserver/config/jwt/JwtAuthenticationEntryPoint.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.HttpStatus; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; @@ -18,15 +19,15 @@ public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { - setResponse(response, ErrorStatus.UNAUTHORIZED_TOKEN); + setResponse(response, HttpStatus.UNAUTHORIZED, ErrorStatus.UNAUTHORIZED_TOKEN); } - public void setResponse(HttpServletResponse response, ErrorStatus status) throws IOException { + public void setResponse(HttpServletResponse response, HttpStatus statusCode, ErrorStatus status) throws IOException { response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - ApiResponseDto apiResponse = ApiResponseDto.error(status); + ApiResponseDto apiResponse = ApiResponseDto.error(statusCode.value(), status.getMessage()); response.getWriter().println(mapper.writeValueAsString(apiResponse)); } } diff --git a/src/main/java/site/katchup/katchupserver/config/jwt/JwtAuthenticationFilter.java b/src/main/java/site/katchup/katchupserver/config/jwt/JwtAuthenticationFilter.java index 3ac1fd4..5edfb4c 100644 --- a/src/main/java/site/katchup/katchupserver/config/jwt/JwtAuthenticationFilter.java +++ b/src/main/java/site/katchup/katchupserver/config/jwt/JwtAuthenticationFilter.java @@ -6,10 +6,11 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter; -import site.katchup.katchupserver.common.exception.CustomException; +import site.katchup.katchupserver.common.exception.UnauthorizedException; import site.katchup.katchupserver.common.response.ErrorStatus; import java.io.IOException; @@ -30,12 +31,12 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse String refreshToken = jwtTokenProvider.resolveRefreshToken(request); if (jwtTokenProvider.validateToken(refreshToken) == JwtExceptionType.EMPTY_JWT || jwtTokenProvider.validateToken(accessToken) == JwtExceptionType.EMPTY_JWT) { - jwtAuthenticationEntryPoint.setResponse(response, ErrorStatus.NO_TOKEN); + jwtAuthenticationEntryPoint.setResponse(response, HttpStatus.BAD_REQUEST, ErrorStatus.NO_TOKEN); return; } else if (jwtTokenProvider.validateToken(accessToken) == JwtExceptionType.EXPIRED_JWT_TOKEN) { if (jwtTokenProvider.validateToken(refreshToken) == JwtExceptionType.EXPIRED_JWT_TOKEN) { // access, refresh 둘 다 만료 - jwtAuthenticationEntryPoint.setResponse(response, ErrorStatus.SIGNIN_REQUIRED); + jwtAuthenticationEntryPoint.setResponse(response, HttpStatus.UNAUTHORIZED, ErrorStatus.SIGNIN_REQUIRED); return; } else if (jwtTokenProvider.validateToken(refreshToken) == JwtExceptionType.VALID_JWT_TOKEN) { // 토큰 재발급 @@ -48,10 +49,10 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse request.setAttribute("newAccessToken", newAccessToken); } } else if (jwtTokenProvider.validateToken(accessToken) == JwtExceptionType.VALID_JWT_TOKEN) { - jwtAuthenticationEntryPoint.setResponse(response, ErrorStatus.VALID_ACCESS_TOKEN); + jwtAuthenticationEntryPoint.setResponse(response, HttpStatus.UNAUTHORIZED, ErrorStatus.VALID_ACCESS_TOKEN); return; } else { - throw new CustomException(ErrorStatus.UNAUTHORIZED_TOKEN); + throw new UnauthorizedException(ErrorStatus.UNAUTHORIZED_TOKEN); } } else { @@ -65,7 +66,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } } } catch (Exception e) { - throw new CustomException(ErrorStatus.UNAUTHORIZED_TOKEN); + throw new UnauthorizedException(ErrorStatus.UNAUTHORIZED_TOKEN); } chain.doFilter(request, response); diff --git a/src/main/java/site/katchup/katchupserver/config/jwt/JwtTokenProvider.java b/src/main/java/site/katchup/katchupserver/config/jwt/JwtTokenProvider.java index 37de1a1..382c6cf 100644 --- a/src/main/java/site/katchup/katchupserver/config/jwt/JwtTokenProvider.java +++ b/src/main/java/site/katchup/katchupserver/config/jwt/JwtTokenProvider.java @@ -10,7 +10,7 @@ import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import site.katchup.katchupserver.api.member.repository.MemberRepository; -import site.katchup.katchupserver.common.exception.CustomException; +import site.katchup.katchupserver.common.exception.UnauthorizedException; import site.katchup.katchupserver.common.response.ErrorStatus; import java.security.Key; @@ -116,7 +116,7 @@ public Long validateMemberRefreshToken(String accessToken, String refreshToken) Claims claims = getAccessTokenPayload(accessToken); Long memberId = Long.valueOf(String.valueOf(claims.get("memberId"))); if (!memberRepository.existsByIdAndRefreshToken(memberId, refreshToken)) { - throw new CustomException(ErrorStatus.INVALID_MEMBER); + throw new UnauthorizedException(ErrorStatus.INVALID_MEMBER); } return memberId; }