diff --git a/app/src/main/kotlin/com/wespot/common/GlobalExceptionHandler.kt b/app/src/main/kotlin/com/wespot/common/GlobalExceptionHandler.kt index 1bceba86..55e66710 100644 --- a/app/src/main/kotlin/com/wespot/common/GlobalExceptionHandler.kt +++ b/app/src/main/kotlin/com/wespot/common/GlobalExceptionHandler.kt @@ -1,15 +1,23 @@ package com.wespot.common +import com.wespot.ReasonPhraseUtil import com.wespot.common.`in`.ErrorNotificationUseCase +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionResponse +import com.wespot.exception.ExceptionView +import feign.FeignException import jakarta.servlet.http.HttpServletRequest -import org.slf4j.LoggerFactory import org.springframework.core.env.Environment +import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus +import org.springframework.http.HttpStatusCode import org.springframework.http.ProblemDetail import org.springframework.http.ResponseEntity -import org.springframework.web.HttpRequestMethodNotSupportedException +import org.springframework.web.bind.MethodArgumentNotValidException import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler +import org.springframework.web.context.request.WebRequest +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler import java.net.URI import java.time.LocalDateTime @@ -17,108 +25,87 @@ import java.time.LocalDateTime class GlobalExceptionHandler( private val errorNotificationUseCase: ErrorNotificationUseCase, private val environment: Environment -) { +) : ResponseEntityExceptionHandler() { - private val logger = LoggerFactory.getLogger(GlobalExceptionHandler::class.java) - - @ExceptionHandler(IllegalArgumentException::class) - fun handleIllegalArgumentException( - exception: IllegalArgumentException, + @ExceptionHandler(CustomException::class) + fun handleCustomException( + exception: CustomException, request: HttpServletRequest - ): ResponseEntity { + ): ResponseEntity { notifyException(false, request, exception) - logger.error("요청된 정보가 잘못되었습니다.", exception) + logger.warn("예외가 발생했습니다.", exception) val problemDetail = ProblemDetail.forStatusAndDetail( - HttpStatus.BAD_REQUEST, + exception.status, exception.message ).apply { - type = URI.create("/errors/illegal-argument") + type = ReasonPhraseUtil.createErrorTypeInProblemDetail("/error", exception.status) instance = URI.create(request.requestURI) } - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body(problemDetail) + return ResponseEntity.status(exception.status) + .body(ExceptionResponse(exception.view, problemDetail)) } - @ExceptionHandler(IllegalStateException::class) - fun handleIllegalStateException( - exception: IllegalStateException, + @ExceptionHandler(Exception::class) + fun handleException( + exception: Exception, request: HttpServletRequest ): ResponseEntity { - notifyException(false, request, exception) - logger.error("잘못된 상태입니다", exception) + notifyException(true, request, exception) + val internalErrorMessage = "서버에서 알 수 없는 에러가 발생했습니다." + logger.error(internalErrorMessage, exception) val problemDetail = ProblemDetail.forStatusAndDetail( - HttpStatus.CONFLICT, - exception.message + HttpStatus.INTERNAL_SERVER_ERROR, + internalErrorMessage ).apply { - type = URI.create("/errors/conflict") + type = ReasonPhraseUtil.createErrorTypeInProblemDetail("/error", HttpStatus.INTERNAL_SERVER_ERROR) instance = URI.create(request.requestURI) } - return ResponseEntity.status(HttpStatus.CONFLICT) + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(problemDetail) } - @ExceptionHandler(HttpRequestMethodNotSupportedException::class) - fun handleHttpRequestMethodNotSupported( - exception: HttpRequestMethodNotSupportedException, + @ExceptionHandler(FeignException::class) + fun handleFeignException( + exception: FeignException, request: HttpServletRequest - ): ResponseEntity { + ): ResponseEntity { notifyException(false, request, exception) - logger.error("지원하지 않는 HTTP 메소드입니다.", exception) + logger.warn("외부 API 호출 중 예외가 발생했습니다.", exception) val problemDetail = ProblemDetail.forStatusAndDetail( HttpStatus.BAD_REQUEST, exception.message ).apply { - type = URI.create("/errors/method-not-supported") + type = ReasonPhraseUtil.createErrorTypeInProblemDetail("/error", HttpStatus.BAD_REQUEST) instance = URI.create(request.requestURI) } return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body(problemDetail) + .body(ExceptionResponse(ExceptionView.TOAST, problemDetail)) } - @ExceptionHandler(NoSuchElementException::class) - fun handleNoSuchElementException( - exception: NoSuchElementException, - request: HttpServletRequest - ): ResponseEntity { - notifyException(false, request, exception) - logger.error("자원을 찾을 수 없습니다.", exception) + override fun handleMethodArgumentNotValid( + exception: MethodArgumentNotValidException, + headers: HttpHeaders, + status: HttpStatusCode, + request: WebRequest + ): ResponseEntity { + logger.warn("잘못된 요청입니다.", exception) val problemDetail = ProblemDetail.forStatusAndDetail( - HttpStatus.NOT_FOUND, + HttpStatus.BAD_REQUEST, exception.message ).apply { - type = URI.create("/errors/no-such-element") - instance = URI.create(request.requestURI) - } - - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(problemDetail) - } - - @ExceptionHandler(Exception::class) - fun handleException( - exception: Exception, - request: HttpServletRequest - ): ResponseEntity { - notifyException(true, request, exception) - logger.error("서버에서 알 수 없는 에러가 발생했습니다.", exception) - - val problemDetail = ProblemDetail.forStatusAndDetail( - HttpStatus.INTERNAL_SERVER_ERROR, - "서버에서 알 수 없는 에러가 발생했습니다." - ).apply { - type = URI.create("/errors/internal-server-error") - instance = URI.create(request.requestURI) + type = ReasonPhraseUtil.createErrorTypeInProblemDetail("/error", HttpStatus.BAD_REQUEST) + instance = URI.create(request.getDescription(false)) } - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(problemDetail) + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(ExceptionResponse(ExceptionView.TOAST, problemDetail)) } private fun notifyException(isError: Boolean, request: HttpServletRequest, exception: Exception) { @@ -136,7 +123,6 @@ class GlobalExceptionHandler( val fullStackTrace = exception.stackTraceToString().take(3000) - // 예외 발생 알림을 디스코드에 전송 errorNotificationUseCase.notifyError( isError, "### 🕖 발생 시간\n" + @@ -169,7 +155,6 @@ class GlobalExceptionHandler( ) } - private fun extractExceptionSource(exception: Exception): String { val stackTrace = exception.stackTrace if (stackTrace.isNotEmpty()) { diff --git a/app/src/main/kotlin/com/wespot/config/FirebaseConfig.kt b/app/src/main/kotlin/com/wespot/config/FirebaseConfig.kt index 3159528e..122b08a4 100644 --- a/app/src/main/kotlin/com/wespot/config/FirebaseConfig.kt +++ b/app/src/main/kotlin/com/wespot/config/FirebaseConfig.kt @@ -3,8 +3,12 @@ package com.wespot.config import com.google.auth.oauth2.GoogleCredentials import com.google.firebase.FirebaseApp import com.google.firebase.FirebaseOptions +import com.wespot.config.security.CustomUrlFilter +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import jakarta.annotation.PostConstruct import org.springframework.context.annotation.Configuration +import org.springframework.http.HttpStatus @Configuration class FirebaseConfig { @@ -21,7 +25,7 @@ class FirebaseConfig { FirebaseApp.initializeApp(options) } } catch (e: Exception) { - throw IllegalArgumentException("Firebase APP 연결에 실패했습니다.", e) + throw CustomException(HttpStatus.INTERNAL_SERVER_ERROR, ExceptionView.DIALOG, "Firebase APP 연결에 실패했습니다.") } } diff --git a/app/src/test/kotlin/com/wespot/auth/service/AuthServiceTest.kt b/app/src/test/kotlin/com/wespot/auth/service/AuthServiceTest.kt index 18bc6405..5794c274 100644 --- a/app/src/test/kotlin/com/wespot/auth/service/AuthServiceTest.kt +++ b/app/src/test/kotlin/com/wespot/auth/service/AuthServiceTest.kt @@ -13,6 +13,8 @@ import com.wespot.auth.fixture.AuthFixture import com.wespot.auth.port.out.AuthDataPort import com.wespot.auth.port.out.RefreshTokenPort import com.wespot.auth.service.jwt.JwtTokenProvider +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.school.port.out.SchoolPort import com.wespot.user.SocialType import com.wespot.user.event.CreatedVoteEvent @@ -31,6 +33,7 @@ import io.mockk.just import io.mockk.mockk import io.mockk.spyk import org.springframework.context.ApplicationEventPublisher +import org.springframework.http.HttpStatus import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.core.Authentication import org.springframework.security.crypto.password.PasswordEncoder @@ -167,10 +170,14 @@ class AuthServiceTest : BehaviorSpec({ } `when`("잘못된 socialType으로 loginAccess를 호출할 때") { - every { authService.fetchSocialEmail(authLoginRequest) } throws NoSuchElementException("잘못된 socialType 입니다") + every { authService.fetchSocialEmail(authLoginRequest) } throws CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "잘못된 socialType 입니다" + ) - then("NoSuchElementException이 발생해야 한다") { - shouldThrow { + then("CustomException 400이 발생해야 한다") { + shouldThrow { authService.socialAccess(authLoginRequest) } } @@ -235,10 +242,14 @@ class AuthServiceTest : BehaviorSpec({ } `when`("잘못된 signUpToken으로 signUp을 호출할 때") { - every { authService.checkSignUpToken(signUpRequest.signUpToken) } throws NoSuchElementException("잘못된 signUpToken 입니다") + every { authService.checkSignUpToken(signUpRequest.signUpToken) } throws CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "잘못된 signUpToken 입니다" + ) - then("NoSuchElementException이 발생해야 한다") { - shouldThrow { + then("CustomException 400이 발생해야 한다") { + shouldThrow { authService.signUp(signUpRequest) } } @@ -334,12 +345,14 @@ class AuthServiceTest : BehaviorSpec({ } `when`("잘못된 refreshToken으로 reIssueToken을 호출할 때") { - every { authenticationService.getAuthentication(refreshTokenRequest.refreshToken) } throws NoSuchElementException( + every { authenticationService.getAuthentication(refreshTokenRequest.refreshToken) } throws CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, "잘못된 refreshToken 입니다" ) - then("NoSuchElementException이 발생해야 한다") { - shouldThrow { + then("CustomException이 Bad Request가 발생해야 한다") { + shouldThrow { authService.reIssueToken(refreshTokenRequest) } } @@ -387,8 +400,8 @@ class AuthServiceTest : BehaviorSpec({ `when`("잘못된 사용자 ID로 revoke를 호출할 때") { every { userPort.findById(user.id) } returns null - then("NoSuchElementException이 발생해야 한다") { - shouldThrow { + then("CustomException Not Found가 발생해야 한다") { + shouldThrow { authService.revoke() } } diff --git a/app/src/test/kotlin/com/wespot/common/domain/ProfanityCheckerTest.kt b/app/src/test/kotlin/com/wespot/common/domain/ProfanityCheckerTest.kt index 248243f7..5e838f22 100644 --- a/app/src/test/kotlin/com/wespot/common/domain/ProfanityCheckerTest.kt +++ b/app/src/test/kotlin/com/wespot/common/domain/ProfanityCheckerTest.kt @@ -1,6 +1,7 @@ package com.wespot.common.domain import com.wespot.common.ProfanityChecker +import com.wespot.exception.CustomException import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec import io.kotest.matchers.shouldBe @@ -23,10 +24,10 @@ class ProfanityCheckerTest : BehaviorSpec({ } } `when`("욕설이 존재하면") { - val shouldThrow1 = shouldThrow { ProfanityChecker.validateContent(badWords[0]) } - val shouldThrow2 = shouldThrow { ProfanityChecker.validateContent(badWords[1]) } - val shouldThrow3 = shouldThrow { ProfanityChecker.validateContent(badWords[2]) } - val shouldThrow4 = shouldThrow { ProfanityChecker.validateContent(badWords[3]) } + val shouldThrow1 = shouldThrow { ProfanityChecker.validateContent(badWords[0]) } + val shouldThrow2 = shouldThrow { ProfanityChecker.validateContent(badWords[1]) } + val shouldThrow3 = shouldThrow { ProfanityChecker.validateContent(badWords[2]) } + val shouldThrow4 = shouldThrow { ProfanityChecker.validateContent(badWords[3]) } then("에외를 발생시킨다.") { shouldThrow1 shouldHaveMessage "비속어가 포함되어 있습니다." shouldThrow2 shouldHaveMessage "비속어가 포함되어 있습니다." diff --git a/app/src/test/kotlin/com/wespot/common/service/CheckProfanityServiceTest.kt b/app/src/test/kotlin/com/wespot/common/service/CheckProfanityServiceTest.kt index 7762c196..8432aae0 100644 --- a/app/src/test/kotlin/com/wespot/common/service/CheckProfanityServiceTest.kt +++ b/app/src/test/kotlin/com/wespot/common/service/CheckProfanityServiceTest.kt @@ -1,6 +1,7 @@ package com.wespot.common.service import com.wespot.common.dto.CheckProfanityRequest +import com.wespot.exception.CustomException import io.kotest.assertions.throwables.shouldNotThrow import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.throwable.shouldHaveMessage @@ -18,7 +19,7 @@ class CheckProfanityServiceTest @Autowired constructor( val checkProfanityRequest = CheckProfanityRequest(validWord) // when then - shouldNotThrow { checkProfanityService.checkProfanity(checkProfanityRequest) } + shouldNotThrow { checkProfanityService.checkProfanity(checkProfanityRequest) } } @Test @@ -29,7 +30,7 @@ class CheckProfanityServiceTest @Autowired constructor( // when val shouldThrow = - shouldThrow { checkProfanityService.checkProfanity(checkProfanityRequest) } + shouldThrow { checkProfanityService.checkProfanity(checkProfanityRequest) } // then shouldThrow shouldHaveMessage "비속어가 포함되어 있습니다." diff --git a/app/src/test/kotlin/com/wespot/common/util/ReasonPhraseUtilTest.kt b/app/src/test/kotlin/com/wespot/common/util/ReasonPhraseUtilTest.kt new file mode 100644 index 00000000..c09f3233 --- /dev/null +++ b/app/src/test/kotlin/com/wespot/common/util/ReasonPhraseUtilTest.kt @@ -0,0 +1,25 @@ +package com.wespot.common.util + +import com.wespot.ReasonPhraseUtil +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test +import org.springframework.http.HttpStatus +import java.net.URI + +class ReasonPhraseUtilTest { + + @Test + fun `HttpStatus내의 ReasonPhrase를 ProblemDetail내의 형식으로 변경한다`() { + // given + val prefixUrl = "/error" + val httpStatus = HttpStatus.BAD_REQUEST + val expected = URI.create("/error/bad-request") + + // when + val actual = ReasonPhraseUtil.createErrorTypeInProblemDetail(prefixUrl, httpStatus) + + // then + actual shouldBe expected + } + +} diff --git a/app/src/test/kotlin/com/wespot/message/domain/MessageContentTest.kt b/app/src/test/kotlin/com/wespot/message/domain/MessageContentTest.kt index 76b4d9d5..0f0d4f73 100644 --- a/app/src/test/kotlin/com/wespot/message/domain/MessageContentTest.kt +++ b/app/src/test/kotlin/com/wespot/message/domain/MessageContentTest.kt @@ -1,5 +1,6 @@ package com.wespot.message.domain +import com.wespot.exception.CustomException import com.wespot.message.MessageContent import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec @@ -13,13 +14,13 @@ class MessageContentTest : BehaviorSpec({ val emptyContent = "" val validContent = "헬로우" `when`("욕설이 포함되어 있는 경우") { - val shouldThrow = shouldThrow { MessageContent.from(badWordsContent) } + val shouldThrow = shouldThrow { MessageContent.from(badWordsContent) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "메시지의 내용에 비속어가 포함되어 있습니다." } } `when`("아무런 내용이 없는 경우") { - val shouldThrow = shouldThrow { MessageContent.from(emptyContent) } + val shouldThrow = shouldThrow { MessageContent.from(emptyContent) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "메시지의 내용은 필수로 존재해야합니다." } diff --git a/app/src/test/kotlin/com/wespot/message/domain/MessageTest.kt b/app/src/test/kotlin/com/wespot/message/domain/MessageTest.kt index ec9f3247..8ba32689 100644 --- a/app/src/test/kotlin/com/wespot/message/domain/MessageTest.kt +++ b/app/src/test/kotlin/com/wespot/message/domain/MessageTest.kt @@ -1,5 +1,6 @@ package com.wespot.message.domain +import com.wespot.exception.CustomException import com.wespot.message.Message import com.wespot.message.MessageTimeValidator import com.wespot.message.fixture.MessageFixture @@ -45,7 +46,7 @@ class MessageTest : BehaviorSpec({ } } `when`("수신하지 않은 자가 메시지를 신고한 경우") { - val shouldThrow = shouldThrow { message.reported(3) } + val shouldThrow = shouldThrow { message.reported(3) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "수신자만이 메시지를 신고할 수 있습니다." @@ -59,7 +60,7 @@ class MessageTest : BehaviorSpec({ val badWordsContent = "ㅂㅁㄴ이;라ㅓ 싮ㅂㅅㅂㅅㅂㅅㅂ시ㅂ 메시지" val emptyContent = "" `when`("욕설이 포함되어 있는 경우") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { Message.sendMessage( badWordsContent, 1, @@ -73,7 +74,7 @@ class MessageTest : BehaviorSpec({ } } `when`("아무런 내용이 없는 경우") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { Message.sendMessage( emptyContent, 1, diff --git a/app/src/test/kotlin/com/wespot/message/service/MessageTimeValidatorTest.kt b/app/src/test/kotlin/com/wespot/message/service/MessageTimeValidatorTest.kt index 6b98bf44..1489ee4a 100644 --- a/app/src/test/kotlin/com/wespot/message/service/MessageTimeValidatorTest.kt +++ b/app/src/test/kotlin/com/wespot/message/service/MessageTimeValidatorTest.kt @@ -1,5 +1,6 @@ package com.wespot.message.service +import com.wespot.exception.CustomException import com.wespot.message.MessageTimeValidator import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec @@ -34,7 +35,7 @@ class MessageTimeValidatorTest : BehaviorSpec({ MessageTimeValidator.setClock(fixedClock) // Act & Assert - val exception = shouldThrow { + val exception = shouldThrow { MessageTimeValidator.validateMessageSendTime() } exception shouldHaveMessage "이미 10시가 지나서 쪽지를 예약할 수 없어요\n아쉽지만 내일 다시 작성해보는 건 어떨까요?" @@ -48,7 +49,7 @@ class MessageTimeValidatorTest : BehaviorSpec({ MessageTimeValidator.setClock(fixedClock) // Act & Assert - val exception = shouldThrow { + val exception = shouldThrow { MessageTimeValidator.validateMessageSendTime() } exception shouldHaveMessage "이미 10시가 지나서 쪽지를 예약할 수 없어요\n아쉽지만 내일 다시 작성해보는 건 어떨까요?" diff --git a/app/src/test/kotlin/com/wespot/notification/domain/NotificationFilterTest.kt b/app/src/test/kotlin/com/wespot/notification/domain/NotificationFilterTest.kt index 845f9027..2c1f7b09 100644 --- a/app/src/test/kotlin/com/wespot/notification/domain/NotificationFilterTest.kt +++ b/app/src/test/kotlin/com/wespot/notification/domain/NotificationFilterTest.kt @@ -1,5 +1,6 @@ package com.wespot.notification.domain +import com.wespot.exception.CustomException import com.wespot.notification.Notification import com.wespot.notification.NotificationFilterService import com.wespot.notification.NotificationType @@ -98,7 +99,7 @@ class NotificationFilterTest : BehaviorSpec({ type = NotificationType.VOTE ) ) - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { notificationFilterService.filterNotifications( users, messageNotifications diff --git a/app/src/test/kotlin/com/wespot/notification/domain/NotificationTest.kt b/app/src/test/kotlin/com/wespot/notification/domain/NotificationTest.kt index d9298644..7cef3864 100644 --- a/app/src/test/kotlin/com/wespot/notification/domain/NotificationTest.kt +++ b/app/src/test/kotlin/com/wespot/notification/domain/NotificationTest.kt @@ -1,5 +1,6 @@ package com.wespot.notification.domain +import com.wespot.exception.CustomException import com.wespot.notification.Notification import com.wespot.notification.NotificationType import io.kotest.assertions.throwables.shouldThrow @@ -62,7 +63,7 @@ class NotificationTest : BehaviorSpec({ } } `when`("쪽지용으로 생성할 때, 잘못된 타입을 입력하면") { - val shouldThrow1 = shouldThrow { + val shouldThrow1 = shouldThrow { Notification.createMessageInitialState( userId = 1, type = NotificationType.VOTE, @@ -71,7 +72,7 @@ class NotificationTest : BehaviorSpec({ body = "테스트" ) } - val shouldThrow2 = shouldThrow { + val shouldThrow2 = shouldThrow { Notification.createMessageInitialState( userId = 1, type = NotificationType.VOTE_RESULT, @@ -80,7 +81,7 @@ class NotificationTest : BehaviorSpec({ body = "테스트" ) } - val shouldThrow3 = shouldThrow { + val shouldThrow3 = shouldThrow { Notification.createMessageInitialState( userId = 1, type = NotificationType.VOTE_RECEIVED, @@ -141,7 +142,7 @@ class NotificationTest : BehaviorSpec({ } `when`("투표용으로 생성할 때, 잘못된 타입을 입력하면") { - val shouldThrow1 = shouldThrow { + val shouldThrow1 = shouldThrow { Notification.createVoteInitialState( userId = 1, type = NotificationType.MESSAGE, @@ -150,7 +151,7 @@ class NotificationTest : BehaviorSpec({ body = "테스트" ) } - val shouldThrow2 = shouldThrow { + val shouldThrow2 = shouldThrow { Notification.createVoteInitialState( userId = 1, type = NotificationType.MESSAGE_SENT, @@ -159,7 +160,7 @@ class NotificationTest : BehaviorSpec({ body = "테스트" ) } - val shouldThrow3 = shouldThrow { + val shouldThrow3 = shouldThrow { Notification.createVoteInitialState( userId = 1, type = NotificationType.MESSAGE_RECEIVED, @@ -209,7 +210,7 @@ class NotificationTest : BehaviorSpec({ title = "테스트", body = "테스트" ) - val shouldThrow = shouldThrow { notification.read(2) } + val shouldThrow = shouldThrow { notification.read(2) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "알림 수신자만 알림을 조회할 수 있습니다." } diff --git a/app/src/test/kotlin/com/wespot/notification/domain/vote/RegisteredVoteNotificationServiceTest.kt b/app/src/test/kotlin/com/wespot/notification/domain/vote/RegisteredVoteNotificationServiceTest.kt index d28bd5be..6669b1ed 100644 --- a/app/src/test/kotlin/com/wespot/notification/domain/vote/RegisteredVoteNotificationServiceTest.kt +++ b/app/src/test/kotlin/com/wespot/notification/domain/vote/RegisteredVoteNotificationServiceTest.kt @@ -1,5 +1,6 @@ package com.wespot.notification.domain.vote +import com.wespot.exception.CustomException import com.wespot.notification.NotificationType import com.wespot.notification.vote.RegisteredVoteNotificationService import com.wespot.user.fixture.UserFixture @@ -116,7 +117,7 @@ class RegisteredVoteNotificationServiceTest : BehaviorSpec({ then("예외가 발생한다.") { val shouldThrow = - shouldThrow { service.getNotifications(users[0], users, vote) } + shouldThrow { service.getNotifications(users[0], users, vote) } shouldThrow shouldHaveMessage "다른 학급의 사용자가 포함되어 있습니다." } } diff --git a/app/src/test/kotlin/com/wespot/notification/domain/vote/SignUpVoteNotificationServiceTest.kt b/app/src/test/kotlin/com/wespot/notification/domain/vote/SignUpVoteNotificationServiceTest.kt index e9dc3f42..f0ba1db0 100644 --- a/app/src/test/kotlin/com/wespot/notification/domain/vote/SignUpVoteNotificationServiceTest.kt +++ b/app/src/test/kotlin/com/wespot/notification/domain/vote/SignUpVoteNotificationServiceTest.kt @@ -1,5 +1,6 @@ package com.wespot.notification.domain.vote +import com.wespot.exception.CustomException import com.wespot.notification.NotificationType import com.wespot.notification.vote.SignUpVoteNotificationService import com.wespot.user.fixture.UserFixture @@ -39,7 +40,7 @@ class SignUpVoteNotificationServiceTest : BehaviorSpec({ UserFixture.createWithIdAndSchoolIdAndGradeAndClassNumber(1, 1, 1, 1), UserFixture.createWithIdAndSchoolIdAndGradeAndClassNumber(2, 1, 1, 2), ) - val shouldThrow = shouldThrow { service.getNotifications(users[0], users) } + val shouldThrow = shouldThrow { service.getNotifications(users[0], users) } then("예외가 발생한다.") { shouldThrow.message shouldBe "다른 학급의 사용자가 포함되어 있습니다." } diff --git a/app/src/test/kotlin/com/wespot/report/domain/ReportTest.kt b/app/src/test/kotlin/com/wespot/report/domain/ReportTest.kt index 5698d631..260a045d 100644 --- a/app/src/test/kotlin/com/wespot/report/domain/ReportTest.kt +++ b/app/src/test/kotlin/com/wespot/report/domain/ReportTest.kt @@ -1,5 +1,6 @@ package com.wespot.report.domain +import com.wespot.exception.CustomException import com.wespot.report.Report import com.wespot.report.ReportType import com.wespot.user.fixture.UserFixture @@ -16,7 +17,7 @@ class ReportTest : BehaviorSpec({ `when`("송신자와 수신자가 동일하면 ") { val shouldThrow = - shouldThrow { Report.of(ReportType.MESSAGE, 1L, sender, receiver) } + shouldThrow { Report.of(ReportType.MESSAGE, 1L, sender, receiver) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "본인이 본인을 신고할 수 없습니다." diff --git a/app/src/test/kotlin/com/wespot/report/domain/RestrictionServiceTest.kt b/app/src/test/kotlin/com/wespot/report/domain/RestrictionServiceTest.kt index 589e5428..355d268d 100644 --- a/app/src/test/kotlin/com/wespot/report/domain/RestrictionServiceTest.kt +++ b/app/src/test/kotlin/com/wespot/report/domain/RestrictionServiceTest.kt @@ -1,5 +1,6 @@ package com.wespot.report.domain +import com.wespot.exception.CustomException import com.wespot.report.Report import com.wespot.report.ReportType import com.wespot.report.RestrictionService @@ -134,7 +135,7 @@ class RestrictionServiceTest : BehaviorSpec({ ReportFixture.createWithReportTypeAndTargetIdAndSenderIdAndReceiverId(ReportType.VOTE, 10, 1, 2) then("예외가 발생한다.") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { restrictionService.calculateRestrictionByReports( originRestriction, report, @@ -151,7 +152,7 @@ class RestrictionServiceTest : BehaviorSpec({ ReportFixture.createWithReportTypeAndTargetIdAndSenderIdAndReceiverId(ReportType.MESSAGE, 1, 1, 2) then("예외가 발생한다.") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { restrictionService.calculateRestrictionByReports( originRestriction, report, @@ -167,7 +168,7 @@ class RestrictionServiceTest : BehaviorSpec({ val report = ReportFixture.createWithReportTypeAndTargetIdAndSenderIdAndReceiverId(ReportType.VOTE, 1, 1, 2) then("예외가 발생하지 않는다.") { - shouldNotThrow { + shouldNotThrow { restrictionService.calculateRestrictionByReports( originRestriction, report, diff --git a/app/src/test/kotlin/com/wespot/report/service/SavedReportServiceTest.kt b/app/src/test/kotlin/com/wespot/report/service/SavedReportServiceTest.kt index 336f6feb..f4c898be 100644 --- a/app/src/test/kotlin/com/wespot/report/service/SavedReportServiceTest.kt +++ b/app/src/test/kotlin/com/wespot/report/service/SavedReportServiceTest.kt @@ -1,6 +1,7 @@ package com.wespot.report.service import com.wespot.common.service.ServiceTest +import com.wespot.exception.CustomException import com.wespot.message.MessageJpaRepository import com.wespot.message.MessageMapper import com.wespot.message.fixture.MessageFixture @@ -37,7 +38,7 @@ class SavedReportServiceTest @Autowired constructor( ) // when - val shouldThrow = shouldThrow { savedReportService.reportReceived(reportRequest) } + val shouldThrow = shouldThrow { savedReportService.reportReceived(reportRequest) } // then shouldThrow shouldHaveMessage "해당 계정이 존재하지 않습니다." @@ -55,7 +56,7 @@ class SavedReportServiceTest @Autowired constructor( ) // when - val shouldThrow = shouldThrow { savedReportService.reportReceived(reportRequest) } + val shouldThrow = shouldThrow { savedReportService.reportReceived(reportRequest) } // then shouldThrow shouldHaveMessage "신고하고자 하는 사용자가 존재하지 않습니다." @@ -73,7 +74,7 @@ class SavedReportServiceTest @Autowired constructor( ) // when - val shouldThrow = shouldThrow { savedReportService.reportReceived(reportRequest) } + val shouldThrow = shouldThrow { savedReportService.reportReceived(reportRequest) } // then shouldThrow shouldHaveMessage "신고하고자 하는 쪽지가 존재하지 않습니다." @@ -104,49 +105,12 @@ class SavedReportServiceTest @Autowired constructor( ) // when - val shouldThrow = shouldThrow { savedReportService.reportReceived(reportRequest) } + val shouldThrow = shouldThrow { savedReportService.reportReceived(reportRequest) } // then shouldThrow shouldHaveMessage "본인이 받은 쪽지가 아닙니다." } - @Test - fun `제보시에, 같은 학급의 친구가 아닌 이를 제보할 경우, 예외가 발생한다`() { - val reportSender = - userJpaRepository.save( - UserMapper.mapToJpaEntity( - UserFixture.createWithEmailAndSchoolIdAndGradeAndClassNumber( - "TestEmail0@Kakao", - 1, - 1, - 1 - ) - ) - ) - UserFixture.setSecurityContextUser(UserMapper.mapToDomainEntity(reportSender)) - val reportReceiver = - userJpaRepository.save( - UserMapper.mapToJpaEntity( - UserFixture.createWithEmailAndSchoolIdAndGradeAndClassNumber( - "TestEmail1@Kakao", - 1, - 1, - 2 - ) - ) - ) - val reportRequest = ReportRequest( - targetId = reportReceiver.id, - reportType = ReportType.VOTE - ) - - // when - val shouldThrow = shouldThrow { savedReportService.reportReceived(reportRequest) } - - // then - shouldThrow shouldHaveMessage "같은 반 친구가 아닙니다." - } - @Test fun `쪽지를 신고하는 경우, 쪽지가 지워진다`() { // given diff --git a/app/src/test/kotlin/com/wespot/user/domain/MessageRestrictionTest.kt b/app/src/test/kotlin/com/wespot/user/domain/MessageRestrictionTest.kt index 272d9f48..5f9c4bdf 100644 --- a/app/src/test/kotlin/com/wespot/user/domain/MessageRestrictionTest.kt +++ b/app/src/test/kotlin/com/wespot/user/domain/MessageRestrictionTest.kt @@ -1,5 +1,6 @@ package com.wespot.user.domain +import com.wespot.exception.CustomException import com.wespot.user.RestrictionType import com.wespot.user.restriction.MessageRestriction import io.kotest.assertions.throwables.shouldThrow @@ -19,31 +20,31 @@ class MessageRestrictionTest : BehaviorSpec({ } } `when`("제재 타입과 일 수를 정확하지 않게 입력하면") { - val shouldThrow1 = shouldThrow { + val shouldThrow1 = shouldThrow { MessageRestriction.of( RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT, 29L ) } - val shouldThrow2 = shouldThrow { + val shouldThrow2 = shouldThrow { MessageRestriction.of( RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT, 31L ) } - val shouldThrow3 = shouldThrow { + val shouldThrow3 = shouldThrow { MessageRestriction.of( RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT, 89L ) } - val shouldThrow4 = shouldThrow { + val shouldThrow4 = shouldThrow { MessageRestriction.of( RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT, 91L ) } - val shouldThrow5 = shouldThrow { + val shouldThrow5 = shouldThrow { MessageRestriction.of( RestrictionType.PERMANENT_BAN_MESSAGE_REPORT, Long.MAX_VALUE - 1 @@ -80,7 +81,7 @@ class MessageRestrictionTest : BehaviorSpec({ } } `when`("쪽지 타입이 아닌 제재를 입력하면") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { MessageRestriction.of( RestrictionType.PERMANENT_BAN_VOTE_REPORT, Long.MAX_VALUE diff --git a/app/src/test/kotlin/com/wespot/user/domain/RestrictionTest.kt b/app/src/test/kotlin/com/wespot/user/domain/RestrictionTest.kt index 737138ee..e18473a9 100644 --- a/app/src/test/kotlin/com/wespot/user/domain/RestrictionTest.kt +++ b/app/src/test/kotlin/com/wespot/user/domain/RestrictionTest.kt @@ -1,5 +1,6 @@ package com.wespot.user.domain +import com.wespot.exception.CustomException import com.wespot.user.RestrictionType import com.wespot.user.restriction.Restriction import io.kotest.assertions.throwables.shouldThrow @@ -27,40 +28,40 @@ class RestrictionTest : BehaviorSpec({ then("예외가 발생한다.") { val initialRestriction = Restriction.createInitialState() val shouldThrow = - shouldThrow { + shouldThrow { initialRestriction.addRestrict( RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT, 29L ) } val shouldThrow1 = - shouldThrow { + shouldThrow { initialRestriction.addRestrict( RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT, 31L ) } val shouldThrow2 = - shouldThrow { + shouldThrow { initialRestriction.addRestrict( RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT, 89L ) } val shouldThrow3 = - shouldThrow { + shouldThrow { initialRestriction.addRestrict( RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT, 91L ) } - val shouldThrow4 = shouldThrow { + val shouldThrow4 = shouldThrow { initialRestriction.addRestrict( RestrictionType.PERMANENT_BAN_MESSAGE_REPORT, Long.MAX_VALUE - 1L ) } - val shouldThrow5 = shouldThrow { + val shouldThrow5 = shouldThrow { initialRestriction.addRestrict( RestrictionType.PERMANENT_BAN_VOTE_REPORT, Long.MAX_VALUE - 1L @@ -100,7 +101,7 @@ class RestrictionTest : BehaviorSpec({ val initialRestriction = Restriction.createInitialState() `when`("None을 추가하면") { val shouldThrow = - shouldThrow { initialRestriction.addRestrict(RestrictionType.NONE, 0) } + shouldThrow { initialRestriction.addRestrict(RestrictionType.NONE, 0) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "RestrictionType.NONE을 추가할 수 없습니다." } diff --git a/app/src/test/kotlin/com/wespot/user/domain/UserIntroductionTest.kt b/app/src/test/kotlin/com/wespot/user/domain/UserIntroductionTest.kt index e63ea2fa..ee985f23 100644 --- a/app/src/test/kotlin/com/wespot/user/domain/UserIntroductionTest.kt +++ b/app/src/test/kotlin/com/wespot/user/domain/UserIntroductionTest.kt @@ -1,5 +1,6 @@ package com.wespot.user.domain +import com.wespot.exception.CustomException import com.wespot.user.UserIntroduction import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec @@ -12,7 +13,7 @@ class UserIntroductionTest : BehaviorSpec({ val badWordsIntroduction = "ㅅㅂㅅㅂㅅㅂㅅㅂㅅㅂㅅㅂㅂㅂㅂㅂㅂ" val validIntroduction = "헬로우" `when`("욕설이 포함되어 있는 경우") { - val shouldThrow = shouldThrow { UserIntroduction.from(badWordsIntroduction) } + val shouldThrow = shouldThrow { UserIntroduction.from(badWordsIntroduction) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "소개에 비속어가 포함되어 있습니다." } diff --git a/app/src/test/kotlin/com/wespot/user/domain/UserTest.kt b/app/src/test/kotlin/com/wespot/user/domain/UserTest.kt index 2b777b21..d2f106a6 100644 --- a/app/src/test/kotlin/com/wespot/user/domain/UserTest.kt +++ b/app/src/test/kotlin/com/wespot/user/domain/UserTest.kt @@ -1,5 +1,6 @@ package com.wespot.user.domain +import com.wespot.exception.CustomException import com.wespot.user.RestrictionType import com.wespot.user.fixture.RestrictionFixture import com.wespot.user.fixture.UserFixture @@ -110,7 +111,7 @@ class UserTest : BehaviorSpec({ val badWordsIntroduction = "ㅅㅂㅅㅂㅅㅂㅅㅂㅅㅂㅅㅂㅂㅂㅂㅂㅂ" `when`("욕설이 포함되어 있는 경우") { val createUser = UserFixture.createWithId(1) - val shouldThrow = shouldThrow { createUser.updateProfile(badWordsIntroduction) } + val shouldThrow = shouldThrow { createUser.updateProfile(badWordsIntroduction) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "소개에 비속어가 포함되어 있습니다." } diff --git a/app/src/test/kotlin/com/wespot/user/domain/VoteRestrictionTest.kt b/app/src/test/kotlin/com/wespot/user/domain/VoteRestrictionTest.kt index 5f887822..82cda0d1 100644 --- a/app/src/test/kotlin/com/wespot/user/domain/VoteRestrictionTest.kt +++ b/app/src/test/kotlin/com/wespot/user/domain/VoteRestrictionTest.kt @@ -1,5 +1,6 @@ package com.wespot.user.domain +import com.wespot.exception.CustomException import com.wespot.user.RestrictionType import com.wespot.user.restriction.VoteRestriction import io.kotest.assertions.throwables.shouldThrow @@ -19,7 +20,7 @@ class VoteRestrictionTest : BehaviorSpec({ } } `when`("제재 타입과 일 수를 정확하지 않게 입력하면") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { VoteRestriction.of( RestrictionType.PERMANENT_BAN_VOTE_REPORT, Long.MAX_VALUE - 1 @@ -40,13 +41,13 @@ class VoteRestrictionTest : BehaviorSpec({ } } `when`("투표 타입이 아닌 제재를 입력하면") { - val shouldThrow1 = shouldThrow { + val shouldThrow1 = shouldThrow { VoteRestriction.of( RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT, 30 ) } - val shouldThrow2 = shouldThrow { + val shouldThrow2 = shouldThrow { VoteRestriction.of( RestrictionType.PERMANENT_BAN_MESSAGE_REPORT, Long.MAX_VALUE diff --git a/app/src/test/kotlin/com/wespot/user/service/BlockedUserServiceTest.kt b/app/src/test/kotlin/com/wespot/user/service/BlockedUserServiceTest.kt index 9d317594..b7dfc48e 100644 --- a/app/src/test/kotlin/com/wespot/user/service/BlockedUserServiceTest.kt +++ b/app/src/test/kotlin/com/wespot/user/service/BlockedUserServiceTest.kt @@ -1,6 +1,7 @@ package com.wespot.user.service import com.wespot.auth.service.SecurityUtils +import com.wespot.exception.CustomException import com.wespot.message.Message import com.wespot.message.MessageType import com.wespot.message.fixture.MessageFixture @@ -66,7 +67,7 @@ class BlockedUserServiceTest : BehaviorSpec({ every { blockedUserPort.existsByBlockerIdAndBlockedIdAndMessageId(receiver.id, sender.id, message.id) } returns true then("예외를 발생시켜야 한다") { - val exception = shouldThrow { + val exception = shouldThrow { blockedUserService.blockedUser(message.id) } exception.message shouldBe "이미 차단된 사용자입니다." @@ -94,7 +95,7 @@ class BlockedUserServiceTest : BehaviorSpec({ every { MessageFinder.findMessageById(sentMessage.id, messagePort) } returns sentMessage then("예외를 발생시켜야 한다") { - val exception = shouldThrow { + val exception = shouldThrow { blockedUserService.blockedUser(sentMessage.id) } exception.message shouldBe "받은 메시지만 차단이 가능합니다." diff --git a/app/src/test/kotlin/com/wespot/vote/domain/BallotTest.kt b/app/src/test/kotlin/com/wespot/vote/domain/BallotTest.kt index b14e34b1..ca4e0323 100644 --- a/app/src/test/kotlin/com/wespot/vote/domain/BallotTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/domain/BallotTest.kt @@ -1,5 +1,6 @@ package com.wespot.vote.domain +import com.wespot.exception.CustomException import com.wespot.vote.Ballot import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec @@ -38,7 +39,7 @@ class BallotTest() : BehaviorSpec({ val throwingCallable = { Ballot.of(voteId, LocalDate.now(), voteOptionId, senderId, receiverId, LocalDateTime.now()) } then("예외가 발생한다.") { - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow.message shouldBe "본인을 투표할 수 없습니다." } } @@ -61,7 +62,7 @@ class BallotTest() : BehaviorSpec({ ) } then("예외가 발생한다.") { - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow.message shouldBe "투표한 시각이 잘못되었습니다." } } diff --git a/app/src/test/kotlin/com/wespot/vote/domain/BallotsAggregatorTest.kt b/app/src/test/kotlin/com/wespot/vote/domain/BallotsAggregatorTest.kt index 5c06de4c..f73d09df 100644 --- a/app/src/test/kotlin/com/wespot/vote/domain/BallotsAggregatorTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/domain/BallotsAggregatorTest.kt @@ -1,5 +1,6 @@ package com.wespot.vote.domain +import com.wespot.exception.CustomException import com.wespot.vote.BallotsAggregator import com.wespot.vote.fixture.BallotFixture import io.kotest.assertions.throwables.shouldThrow @@ -13,7 +14,7 @@ class BallotsAggregatorTest : BehaviorSpec({ given("투표지 집계기를 생성할 때") { `when`("서로 다른 선택지에 대한 결과가 섞여 있으면") { then("예외가 발생한다.") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { BallotsAggregator.of( 1L, listOf(BallotFixture.createByVoteAndVoteOptionAndSenderAndReceiver(1L, 2L, 1L, 2L)) diff --git a/app/src/test/kotlin/com/wespot/vote/domain/BallotsTest.kt b/app/src/test/kotlin/com/wespot/vote/domain/BallotsTest.kt index fc6d7914..66ac2efe 100644 --- a/app/src/test/kotlin/com/wespot/vote/domain/BallotsTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/domain/BallotsTest.kt @@ -1,5 +1,6 @@ package com.wespot.vote.domain +import com.wespot.exception.CustomException import com.wespot.vote.Ballots import com.wespot.vote.fixture.BallotFixture import io.kotest.assertions.throwables.shouldThrow @@ -35,7 +36,7 @@ class BallotsTest : BehaviorSpec({ duplicateBallots.add(duplicateBallot) val throwingCallable = { Ballots.from(duplicateBallots) } then("예외가 발생한다.") { - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow shouldHaveMessage "하루에 한 명의 회원에게 한 개의 투표만 할 수 있습니다." } } @@ -50,7 +51,7 @@ class BallotsTest : BehaviorSpec({ ) val throwingCallable = { actual.add(duplicateBallot) } then("예외가 발생한다.") { - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow shouldHaveMessage "하루에 한 명의 회원에게 한 개의 투표만 할 수 있습니다." } } diff --git a/app/src/test/kotlin/com/wespot/vote/domain/CompleteBallotTest.kt b/app/src/test/kotlin/com/wespot/vote/domain/CompleteBallotTest.kt index 2394f11e..1d591b55 100644 --- a/app/src/test/kotlin/com/wespot/vote/domain/CompleteBallotTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/domain/CompleteBallotTest.kt @@ -1,5 +1,6 @@ package com.wespot.vote.domain +import com.wespot.exception.CustomException import com.wespot.user.fixture.UserFixture import com.wespot.vote.CompleteBallot import com.wespot.vote.fixture.BallotFixture @@ -24,7 +25,7 @@ class CompleteBallotTest : BehaviorSpec({ val validVoteOption = VoteOptionFixture.createWithId(1) val invalidVoteOption = VoteOptionFixture.createWithId(2) `when`("입력된 값이 투표지와 동일하지 않다면") { - val shouldThrow1 = shouldThrow { + val shouldThrow1 = shouldThrow { CompleteBallot.of( invalidVote, validVoteOption, @@ -33,7 +34,7 @@ class CompleteBallotTest : BehaviorSpec({ ballot ) } - val shouldThrow2 = shouldThrow { + val shouldThrow2 = shouldThrow { CompleteBallot.of( validVote, invalidVoteOption, @@ -42,7 +43,7 @@ class CompleteBallotTest : BehaviorSpec({ ballot ) } - val shouldThrow3 = shouldThrow { + val shouldThrow3 = shouldThrow { CompleteBallot.of( validVote, validVoteOption, @@ -51,7 +52,7 @@ class CompleteBallotTest : BehaviorSpec({ ballot ) } - val shouldThrow4 = shouldThrow { + val shouldThrow4 = shouldThrow { CompleteBallot.of( validVote, validVoteOption, diff --git a/app/src/test/kotlin/com/wespot/vote/domain/RateTest.kt b/app/src/test/kotlin/com/wespot/vote/domain/RateTest.kt index bb10a0c1..0847d52e 100644 --- a/app/src/test/kotlin/com/wespot/vote/domain/RateTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/domain/RateTest.kt @@ -1,5 +1,6 @@ package com.wespot.vote.domain +import com.wespot.exception.CustomException import com.wespot.vote.Rate import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec @@ -12,7 +13,7 @@ class RateTest : BehaviorSpec({ val validRate = 1 `when`("0 이하의 등수가 입력되면") { then("예외가 발생한다.") { - val shouldThrow = shouldThrow { Rate.from(0) } + val shouldThrow = shouldThrow { Rate.from(0) } shouldThrow shouldHaveMessage "등수는 0 이하일 수 없습니다." } } diff --git a/app/src/test/kotlin/com/wespot/vote/domain/VoteOptionsByVoteDateTest.kt b/app/src/test/kotlin/com/wespot/vote/domain/VoteOptionsByVoteDateTest.kt index e4367fc4..7083d62d 100644 --- a/app/src/test/kotlin/com/wespot/vote/domain/VoteOptionsByVoteDateTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/domain/VoteOptionsByVoteDateTest.kt @@ -1,5 +1,6 @@ package com.wespot.vote.domain +import com.wespot.exception.CustomException import com.wespot.vote.VoteOptionsByVoteDate import com.wespot.voteoption.fixture.VoteOptionFixture import io.kotest.assertions.throwables.shouldNotThrow @@ -42,7 +43,7 @@ class VoteOptionsByVoteDateTest : BehaviorSpec({ { VoteOptionsByVoteDate.createInitialVoteOptionsByVoteDate(0,LocalDate.now(), 1, voteOptions) } then("예외가 발생한다.") { - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow shouldHaveMessage "선택지의 개수가 5의 배수가 아닙니다." } } @@ -65,7 +66,7 @@ class VoteOptionsByVoteDateTest : BehaviorSpec({ ) } then("예외가 발생한다.") { - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow shouldHaveMessage "미래의 선택지는 정할 수 없습니다." } } @@ -97,14 +98,14 @@ class VoteOptionsByVoteDateTest : BehaviorSpec({ ) ) `when`("오늘의 선택지에 포함되어 있지 않은 경우") { - val shouldThrow = shouldThrow { voteOptions.validateVoteOption(6L) } + val shouldThrow = shouldThrow { voteOptions.validateVoteOption(6L) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "오늘 제공된 질문지만 선택해 투표할 수 있습니다." } } `when`("오늘의 선택지에 포함되어 있는 경우") { then("예외가 발생하지 않는다.") { - shouldNotThrow { voteOptions.validateVoteOption(5L) } + shouldNotThrow { voteOptions.validateVoteOption(5L) } } } } diff --git a/app/src/test/kotlin/com/wespot/vote/domain/VoteRecordTest.kt b/app/src/test/kotlin/com/wespot/vote/domain/VoteRecordTest.kt index c1f0d754..82761012 100644 --- a/app/src/test/kotlin/com/wespot/vote/domain/VoteRecordTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/domain/VoteRecordTest.kt @@ -1,5 +1,6 @@ package com.wespot.vote.domain +import com.wespot.exception.CustomException import com.wespot.user.fixture.UserFixture import com.wespot.vote.VoteMetrics import com.wespot.vote.VoteRecord @@ -26,7 +27,7 @@ class VoteRecordTest : BehaviorSpec({ `when`("VoteRecord를 생성할 때, VoteMetrics내의 userId와 입력된 userId가 일치하지 않으면") { val invalidUser = UserFixture.createWithId(2L) then("예외가 발생한다.") { - val shouldThrow = shouldThrow { VoteRecord.of(invalidUser, voteMetrics) } + val shouldThrow = shouldThrow { VoteRecord.of(invalidUser, voteMetrics) } shouldThrow shouldHaveMessage "userId가 일치하지 않습니다." } } @@ -34,7 +35,7 @@ class VoteRecordTest : BehaviorSpec({ `when`("VoteRecord를 생성할 때, 등수가 0 이하이면") { then("예외가 발생한다.") { val shouldThrow = - shouldThrow { VoteRecord.ofWithRate(user, 0, voteMetrics) } + shouldThrow { VoteRecord.ofWithRate(user, 0, voteMetrics) } shouldThrow shouldHaveMessage "등수는 0 이하일 수 없습니다." } } diff --git a/app/src/test/kotlin/com/wespot/vote/domain/VoteTest.kt b/app/src/test/kotlin/com/wespot/vote/domain/VoteTest.kt index e1fcc31f..4a51a525 100644 --- a/app/src/test/kotlin/com/wespot/vote/domain/VoteTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/domain/VoteTest.kt @@ -1,5 +1,6 @@ package com.wespot.vote.domain +import com.wespot.exception.CustomException import com.wespot.user.User import com.wespot.user.fixture.UserFixture import com.wespot.vote.RankCalculateService @@ -49,7 +50,7 @@ class VoteTest() : BehaviorSpec({ val throwingCallable = { Vote.of(voteIdentifier, voteOptions, Vote.of(voteIdentifier, voteOptions, vote)) } then("예외가 발생한다.") { - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow shouldHaveMessage "선택지의 개수가 5의 배수가 아닙니다." } } @@ -66,7 +67,7 @@ class VoteTest() : BehaviorSpec({ } then("예외를 발생시킨다.") { - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow shouldHaveMessage "선택지는 최소 5개 이상이어야 합니다." } } @@ -85,7 +86,7 @@ class VoteTest() : BehaviorSpec({ vote.addBallot(1, users[0], users[1], LocalDateTime.now()) then("예외가 발생한다.") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { vote.addBallot( 1L, users[0], @@ -106,7 +107,7 @@ class VoteTest() : BehaviorSpec({ vote.addBallot(1, users[0], users[1], LocalDateTime.now()) then("정상적으로 투표가 진행된다.") { - shouldNotThrow { + shouldNotThrow { vote.addBallot( 1L, users[1], @@ -125,7 +126,7 @@ class VoteTest() : BehaviorSpec({ ) then("예외가 발생한다.") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { vote.addBallot( 6L, users[0], @@ -401,7 +402,7 @@ class VoteTest() : BehaviorSpec({ } then("예외가 발생한다.") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { vote.getUserReceivedVote( voteOptions[5], users[0], @@ -552,7 +553,7 @@ class VoteTest() : BehaviorSpec({ val previousVote = Vote.of(firstUserVoteIdentifier, voteOptions, null) val secondUserVoteIdentifier = VoteIdentifier.of(secondUser, now) val shouldThrow = - shouldThrow { Vote.of(secondUserVoteIdentifier, voteOptions, previousVote) } + shouldThrow { Vote.of(secondUserVoteIdentifier, voteOptions, previousVote) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "입력된 이전 투표가 유효하지 않습니다." @@ -567,7 +568,7 @@ class VoteTest() : BehaviorSpec({ val previousVote = Vote.of(firstUserVoteIdentifier, voteOptions, null) val secondUserVoteIdentifier = VoteIdentifier.of(secondUser, now) val shouldThrow = - shouldThrow { Vote.of(secondUserVoteIdentifier, voteOptions, previousVote) } + shouldThrow { Vote.of(secondUserVoteIdentifier, voteOptions, previousVote) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "입력된 이전 투표가 유효하지 않습니다." @@ -613,12 +614,12 @@ class VoteTest() : BehaviorSpec({ val voteOptions = createVoteOptionByCount(5) val vote = Vote.of(voteIdentifier, voteOptions, null) val shouldThrow1 = - shouldThrow { vote.findUsersForVote(classmates, otherClassmateUser) } + shouldThrow { vote.findUsersForVote(classmates, otherClassmateUser) } val user = UserFixture.createWithSchoolIdAndGradeAndClassNumber(1, 1, 1) classmates.add(UserFixture.createWithSchoolIdAndGradeAndClassNumber(1, 1, 2)) val shouldThrow2 = - shouldThrow { vote.findUsersForVote(classmates, user) } + shouldThrow { vote.findUsersForVote(classmates, user) } then("예외가 발생한다.") { shouldThrow1 shouldHaveMessage "다른 반의 학생이(을) 투표할 수 없습니다." @@ -635,9 +636,9 @@ class VoteTest() : BehaviorSpec({ val vote = Vote.of(voteIdentifier, voteOptions, null) val otherClassmate = UserFixture.createWithSchoolIdAndGradeAndClassNumber(1, 1, 2) val shouldThrow1 = - shouldThrow { vote.addBallot(1, user, otherClassmate, LocalDateTime.now()) } + shouldThrow { vote.addBallot(1, user, otherClassmate, LocalDateTime.now()) } val shouldThrow2 = - shouldThrow { vote.addBallot(1, otherClassmate, user, LocalDateTime.now()) } + shouldThrow { vote.addBallot(1, otherClassmate, user, LocalDateTime.now()) } then("예외가 발생한다.") { shouldThrow1 shouldHaveMessage "다른 반의 학생이(을) 투표할 수 없습니다." shouldThrow2 shouldHaveMessage "다른 반의 학생이(을) 투표할 수 없습니다." diff --git a/app/src/test/kotlin/com/wespot/vote/service/CreatedVoteServiceTest.kt b/app/src/test/kotlin/com/wespot/vote/service/CreatedVoteServiceTest.kt index d44220b1..57807dc4 100644 --- a/app/src/test/kotlin/com/wespot/vote/service/CreatedVoteServiceTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/service/CreatedVoteServiceTest.kt @@ -1,6 +1,7 @@ package com.wespot.vote.service import com.wespot.common.service.ServiceTest +import com.wespot.exception.CustomException import com.wespot.user.fixture.UserFixture import com.wespot.user.mapper.UserMapper import com.wespot.user.repository.UserJpaRepository @@ -21,6 +22,7 @@ import io.kotest.matchers.throwable.shouldHaveMessage import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.annotation.CustomAutowireConfigurer import java.time.LocalDate class CreatedVoteServiceTest @Autowired constructor( @@ -170,7 +172,7 @@ class CreatedVoteServiceTest @Autowired constructor( @Test fun `가입하지 않은 유저가 투표 생성을 요청할 경우 예외가 발생한다`() { // given when - val shouldThrow = shouldThrow { createdVoteService.createVoteByUser(users[0]) } + val shouldThrow = shouldThrow { createdVoteService.createVoteByUser(users[0]) } // then shouldThrow shouldHaveMessage "ID에 해당하는 사용자가 존재하지 않습니다." diff --git a/app/src/test/kotlin/com/wespot/vote/service/ReceivedVoteServiceTest.kt b/app/src/test/kotlin/com/wespot/vote/service/ReceivedVoteServiceTest.kt index ce4dbeb4..7482c447 100644 --- a/app/src/test/kotlin/com/wespot/vote/service/ReceivedVoteServiceTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/service/ReceivedVoteServiceTest.kt @@ -2,6 +2,7 @@ package com.wespot.vote.service import com.wespot.DatabaseCleanup import com.wespot.common.service.ServiceTest +import com.wespot.exception.CustomException import com.wespot.user.entity.UserJpaEntity import com.wespot.user.fixture.UserFixture import com.wespot.user.mapper.UserMapper @@ -189,7 +190,7 @@ class ReceivedVoteServiceTest @Autowired constructor( ) // when - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { receivedVoteService.getReceivedVote( voteOptions[8].id, now.toLocalDate() diff --git a/app/src/test/kotlin/com/wespot/vote/service/SavedVoteServiceTest.kt b/app/src/test/kotlin/com/wespot/vote/service/SavedVoteServiceTest.kt index 47b302e5..d5ebd390 100644 --- a/app/src/test/kotlin/com/wespot/vote/service/SavedVoteServiceTest.kt +++ b/app/src/test/kotlin/com/wespot/vote/service/SavedVoteServiceTest.kt @@ -2,6 +2,7 @@ package com.wespot.vote.service import com.wespot.DatabaseCleanup import com.wespot.common.service.ServiceTest +import com.wespot.exception.CustomException import com.wespot.notification.port.out.NotificationPort import com.wespot.user.entity.UserJpaEntity import com.wespot.user.fixture.UserFixture @@ -91,7 +92,7 @@ class SavedVoteServiceTest @Autowired constructor( val throwingCallable = { voteService.saveVote(requests) } // then - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow shouldHaveMessage "투표하고자 하는 회원이 존재하지 않습니다." } @@ -133,7 +134,7 @@ class SavedVoteServiceTest @Autowired constructor( val throwingCallable = { voteService.saveVote(requests) } // then - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow shouldHaveMessage "투표는 한번에 최대 5명에게 할 수 있습니다." } @@ -155,7 +156,7 @@ class SavedVoteServiceTest @Autowired constructor( val throwingCallable = { voteService.saveVote(requests) } // then - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow shouldHaveMessage "오늘 제공된 질문지만 선택해 투표할 수 있습니다." } diff --git a/app/src/test/kotlin/com/wespot/voteoption/domain/VoteOptionContentTest.kt b/app/src/test/kotlin/com/wespot/voteoption/domain/VoteOptionContentTest.kt index f070c028..131a1abe 100644 --- a/app/src/test/kotlin/com/wespot/voteoption/domain/VoteOptionContentTest.kt +++ b/app/src/test/kotlin/com/wespot/voteoption/domain/VoteOptionContentTest.kt @@ -1,5 +1,6 @@ package com.wespot.voteoption.domain +import com.wespot.exception.CustomException import com.wespot.voteoption.VoteOptionContent import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec @@ -11,7 +12,7 @@ class VoteOptionContentTest : BehaviorSpec({ given("선택지에") { val badWordsContent = "ㅂㅁㄴ이;라ㅓ 싮ㅂㅅㅂㅅㅂㅅㅂ시ㅂ 선택지" `when`("욕설이 포함되어 있는 경우") { - val shouldThrow = shouldThrow { VoteOptionContent.from(badWordsContent) } + val shouldThrow = shouldThrow { VoteOptionContent.from(badWordsContent) } then("예외가 발생한다.") { shouldThrow shouldHaveMessage "선택지의 내용에 비속어가 포함되어 있습니다." } diff --git a/app/src/test/kotlin/com/wespot/voteoption/domain/VoteOptionTest.kt b/app/src/test/kotlin/com/wespot/voteoption/domain/VoteOptionTest.kt index 9652c0b4..63155282 100644 --- a/app/src/test/kotlin/com/wespot/voteoption/domain/VoteOptionTest.kt +++ b/app/src/test/kotlin/com/wespot/voteoption/domain/VoteOptionTest.kt @@ -1,5 +1,6 @@ package com.wespot.voteoption.domain +import com.wespot.exception.CustomException import com.wespot.voteoption.VoteOption import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec @@ -31,7 +32,7 @@ class VoteOptionTest() : BehaviorSpec() { given("선택지에") { val badWordsContent = "ㅅㅂㅂㅂㅂㅂㅂㅂㅂㅂ 선택지" `when`("욕설이 포함되어 있는 경우") { - val shouldThrow = shouldThrow { + val shouldThrow = shouldThrow { VoteOption.of( 0L, badWordsContent, @@ -58,7 +59,7 @@ class VoteOptionTest() : BehaviorSpec() { val throwingCallable = { VoteOption.of(id, invalidContent, createdAt, updatedAt) } // then - val shouldThrow = shouldThrow(throwingCallable) + val shouldThrow = shouldThrow(throwingCallable) shouldThrow.message shouldBe "선택지의 내용은 필수로 존재해야합니다." } diff --git a/common/src/main/kotlin/com/wespot/ReasonPhraseUtil.kt b/common/src/main/kotlin/com/wespot/ReasonPhraseUtil.kt new file mode 100644 index 00000000..fc01d70e --- /dev/null +++ b/common/src/main/kotlin/com/wespot/ReasonPhraseUtil.kt @@ -0,0 +1,18 @@ +package com.wespot + +import org.springframework.http.HttpStatus +import java.net.URI + +object ReasonPhraseUtil { + + fun createErrorTypeInProblemDetail(prefixUrl: String, httpStatus: HttpStatus): URI { + return URI.create("${prefixUrl}/${getReasonPhraseWithHyphen(httpStatus.reasonPhrase)}") + } + + private fun getReasonPhraseWithHyphen(reasonPhrase: String): String { + val hyphen = "-" + return reasonPhrase.lowercase() + .replace(" ", hyphen) + } + +} diff --git a/common/src/main/kotlin/com/wespot/error/CustomErrorDecoder.kt b/common/src/main/kotlin/com/wespot/error/CustomErrorDecoder.kt index 5125832c..26212d05 100644 --- a/common/src/main/kotlin/com/wespot/error/CustomErrorDecoder.kt +++ b/common/src/main/kotlin/com/wespot/error/CustomErrorDecoder.kt @@ -1,17 +1,43 @@ package com.wespot.error +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import feign.Response import feign.codec.ErrorDecoder -import java.util.NoSuchElementException +import org.springframework.http.HttpStatus class CustomErrorDecoder : ErrorDecoder { override fun decode(methodKey: String, response: Response): Exception { return when (response.status()) { - 400 -> IllegalArgumentException("OAuth 요청이 잘못되었습니다 (Bad request)") - 401 -> IllegalArgumentException("OAuth 인증에 실패하였습니다 (Authentication failed)") - 404 -> NoSuchElementException("OAuth 리소스를 찾을 수 없습니다 (Resource not found)") - 500 -> RuntimeException("OAuth 내부 서버 오류입니다 (Internal server error)") - else -> RuntimeException("OAuth 연결 중 알 수 없는 오류가 발생했습니다)") + 400 -> CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "OAuth 요청이 잘못되었습니다 (Bad request)" + ) + + 401 -> CustomException( + HttpStatus.UNAUTHORIZED, + ExceptionView.TOAST, + "OAuth 인증에 실패하였습니다 (Authentication failed)" + ) + + 404 -> CustomException( + HttpStatus.NOT_FOUND, + ExceptionView.TOAST, + "OAuth 리소스를 찾을 수 없습니다 (Resource not found)" + ) + + 500 -> CustomException( + HttpStatus.INTERNAL_SERVER_ERROR, + ExceptionView.TOAST, + "OAuth 내부 서버 오류입니다 (Internal server error)" + ) + + else -> CustomException( + HttpStatus.INTERNAL_SERVER_ERROR, + ExceptionView.TOAST, + "OAuth 연결 중 알 수 없는 오류가 발생했습니다)" + ) } } } diff --git a/common/src/main/kotlin/com/wespot/exception/CustomException.kt b/common/src/main/kotlin/com/wespot/exception/CustomException.kt new file mode 100644 index 00000000..1139f68a --- /dev/null +++ b/common/src/main/kotlin/com/wespot/exception/CustomException.kt @@ -0,0 +1,11 @@ +package com.wespot.exception + +import org.springframework.http.HttpStatus + +class CustomException( + val status: HttpStatus, + val view: ExceptionView, + override val message: String, +) : RuntimeException() { + +} diff --git a/common/src/main/kotlin/com/wespot/exception/ExceptionResponse.kt b/common/src/main/kotlin/com/wespot/exception/ExceptionResponse.kt new file mode 100644 index 00000000..26af20ec --- /dev/null +++ b/common/src/main/kotlin/com/wespot/exception/ExceptionResponse.kt @@ -0,0 +1,9 @@ +package com.wespot.exception + +import org.springframework.http.ProblemDetail + +class ExceptionResponse( + val view: ExceptionView, + val problemDetail: ProblemDetail +) { +} diff --git a/common/src/main/kotlin/com/wespot/exception/ExceptionView.kt b/common/src/main/kotlin/com/wespot/exception/ExceptionView.kt new file mode 100644 index 00000000..dd7e79aa --- /dev/null +++ b/common/src/main/kotlin/com/wespot/exception/ExceptionView.kt @@ -0,0 +1,9 @@ +package com.wespot.exception + +enum class ExceptionView { + + TOAST, + DIALOG, + REDIRECT + +} diff --git a/core/src/main/kotlin/com/wespot/auth/dto/apple/ApplePublicKeysResult.kt b/core/src/main/kotlin/com/wespot/auth/dto/apple/ApplePublicKeysResult.kt index 5ead7dce..a157383c 100644 --- a/core/src/main/kotlin/com/wespot/auth/dto/apple/ApplePublicKeysResult.kt +++ b/core/src/main/kotlin/com/wespot/auth/dto/apple/ApplePublicKeysResult.kt @@ -1,5 +1,9 @@ package com.wespot.auth.dto.apple +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus + /** * https://developer.apple.com/documentation/sign_in_with_apple/fetch_apple_s_public_key_for_verifying_token_signature 참고 */ @@ -10,6 +14,10 @@ data class ApplePublicKeysResult( fun getMatchesKey(alg: String?, kid: String?): ApplePublicKey { return keys .firstOrNull { key -> key.alg == alg && key.kid == kid } - ?: throw IllegalArgumentException("Apple JWT 값의 alg, kid 정보가 올바르지 않습니다.") + ?: throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "Apple JWT 값의 alg, kid 정보가 올바르지 않습니다." + ) } } diff --git a/core/src/main/kotlin/com/wespot/auth/service/AuthService.kt b/core/src/main/kotlin/com/wespot/auth/service/AuthService.kt index a55dc2f5..3251967c 100644 --- a/core/src/main/kotlin/com/wespot/auth/service/AuthService.kt +++ b/core/src/main/kotlin/com/wespot/auth/service/AuthService.kt @@ -14,6 +14,8 @@ import com.wespot.auth.port.`in`.AuthUseCase import com.wespot.auth.port.out.AuthDataPort import com.wespot.auth.port.out.RefreshTokenPort import com.wespot.auth.service.jwt.JwtTokenProvider +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.school.port.out.SchoolPort import com.wespot.user.ConsentType import com.wespot.user.FCM @@ -29,7 +31,9 @@ import com.wespot.user.port.out.ProfilePort import com.wespot.user.port.out.UserConsentPort import com.wespot.user.port.out.UserPort import org.springframework.beans.factory.annotation.Value +import org.springframework.beans.propertyeditors.CustomMapEditor import org.springframework.context.ApplicationEventPublisher +import org.springframework.http.HttpStatus import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Service @@ -127,7 +131,7 @@ class AuthService( signUpRequest: SignUpRequest ): User { val school = (schoolPort.findById(signUpRequest.schoolId) - ?: throw NoSuchElementException("해당 학교가 존재하지 않습니다.")) + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "해당 학교가 존재하지 않습니다.")) val social = Social.create( email = signUpToken.email, @@ -195,7 +199,7 @@ class AuthService( override fun revoke() { val loginUserId = getLoginUserId() val revokeUser = userPort.findById(loginUserId) - ?: throw NoSuchElementException("해당 계정이 존재하지 않습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "해당 계정이 존재하지 않습니다.") socialAuthServiceFactory.getService(revokeUser.social.socialType) .revoke(revokeUser.social.socialId, revokeUser.social.socialRefreshToken) @@ -212,7 +216,7 @@ class AuthService( fun getUserByEmail(email: String): User { return userPort.findByEmail(email) - ?: throw NoSuchElementException("유저를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "유저를 찾을 수 없습니다.") } private fun authenticateUser(signInRequest: SignInRequest) = @@ -236,7 +240,11 @@ class AuthService( } fun checkSignUpToken(token: String): AuthData { - return authDataPort.getAuthData(token) ?: throw NoSuchElementException("회원가입 토큰이 만료되었습니다.") + return authDataPort.getAuthData(token) ?: throw CustomException( + HttpStatus.FORBIDDEN, + ExceptionView.TOAST, + "회원가입 토큰이 만료되었습니다." + ) } fun getLoginUserId(): Long { diff --git a/core/src/main/kotlin/com/wespot/auth/service/PrincipalDetailService.kt b/core/src/main/kotlin/com/wespot/auth/service/PrincipalDetailService.kt index 88c329d8..68955b83 100644 --- a/core/src/main/kotlin/com/wespot/auth/service/PrincipalDetailService.kt +++ b/core/src/main/kotlin/com/wespot/auth/service/PrincipalDetailService.kt @@ -1,19 +1,25 @@ package com.wespot.auth.service import com.wespot.auth.PrincipalDetails +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User import com.wespot.user.port.out.UserPort +import org.springframework.http.HttpStatus import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.stereotype.Service -import java.util.NoSuchElementException @Service class PrincipalDetailService( private val userPort: UserPort ) : UserDetailsService { override fun loadUserByUsername(userEmail: String): UserDetails { - val principal: User = userPort.findByEmail(userEmail) ?: throw NoSuchElementException("유저를 찾을 수 없습니다.") + val principal: User = userPort.findByEmail(userEmail) ?: throw CustomException( + HttpStatus.NOT_FOUND, + ExceptionView.TOAST, + "유저를 찾을 수 없습니다." + ) return PrincipalDetails(principal) } diff --git a/core/src/main/kotlin/com/wespot/auth/service/SecurityUtils.kt b/core/src/main/kotlin/com/wespot/auth/service/SecurityUtils.kt index 6bf045f5..8f6b6977 100644 --- a/core/src/main/kotlin/com/wespot/auth/service/SecurityUtils.kt +++ b/core/src/main/kotlin/com/wespot/auth/service/SecurityUtils.kt @@ -2,21 +2,23 @@ package com.wespot.auth.service import com.wespot.auth.PrincipalDetails +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User import com.wespot.user.port.out.UserPort +import org.springframework.http.HttpStatus import org.springframework.security.core.context.SecurityContextHolder -object SecurityUtils -{ - fun getLoginUserId(userPort : UserPort) : Long{ +object SecurityUtils { + fun getLoginUserId(userPort: UserPort): Long { val principal = SecurityContextHolder.getContext().authentication.principal as PrincipalDetails return userPort.findByEmail(principal.username)?.id - ?: throw NoSuchElementException("해당 계정이 존재하지 않습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "해당 계정이 존재하지 않습니다.") } - fun getLoginUser(userPort : UserPort) : User { + fun getLoginUser(userPort: UserPort): User { val principal = SecurityContextHolder.getContext().authentication.principal as PrincipalDetails return userPort.findByEmail(principal.username) - ?: throw NoSuchElementException("해당 계정이 존재하지 않습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "해당 계정이 존재하지 않습니다.") } -} \ No newline at end of file +} diff --git a/core/src/main/kotlin/com/wespot/auth/service/SocialAuthServiceFactory.kt b/core/src/main/kotlin/com/wespot/auth/service/SocialAuthServiceFactory.kt index 705c66f5..d28a9f56 100644 --- a/core/src/main/kotlin/com/wespot/auth/service/SocialAuthServiceFactory.kt +++ b/core/src/main/kotlin/com/wespot/auth/service/SocialAuthServiceFactory.kt @@ -1,6 +1,9 @@ package com.wespot.auth.service +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.SocialType +import org.springframework.http.HttpStatus import org.springframework.stereotype.Service @Service @@ -9,6 +12,10 @@ class SocialAuthServiceFactory( ) { fun getService(socialType: SocialType): SocialAuthService { return services.find { it.isSupport(socialType) } - ?: throw IllegalArgumentException("해당 소셜로그인을 지원하지 않습니다. social type: $socialType") + ?: throw CustomException( + HttpStatus.INTERNAL_SERVER_ERROR, + ExceptionView.TOAST, + "해당 소셜로그인을 지원하지 않습니다. social type: $socialType" + ) } } diff --git a/core/src/main/kotlin/com/wespot/auth/service/apple/AppleCreateClientSecret.kt b/core/src/main/kotlin/com/wespot/auth/service/apple/AppleCreateClientSecret.kt index 57dfdc55..1303f267 100644 --- a/core/src/main/kotlin/com/wespot/auth/service/apple/AppleCreateClientSecret.kt +++ b/core/src/main/kotlin/com/wespot/auth/service/apple/AppleCreateClientSecret.kt @@ -1,11 +1,14 @@ package com.wespot.auth.service.apple +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import io.jsonwebtoken.Jwts import io.jsonwebtoken.SignatureAlgorithm import org.bouncycastle.asn1.pkcs.PrivateKeyInfo import org.bouncycastle.openssl.PEMParser import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter import org.springframework.beans.factory.annotation.Value +import org.springframework.http.HttpStatus import org.springframework.stereotype.Component import java.io.StringReader import java.security.PrivateKey @@ -51,7 +54,7 @@ class AppleCreateClientSecret( val objects = pemParser.readObject() as PrivateKeyInfo converter.getPrivateKey(objects) } catch (e: Exception) { - throw IllegalArgumentException ("Apple private key 생성 실패: ${e.message}") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "Apple private key 생성 실패: ${e.message}") } } } diff --git a/core/src/main/kotlin/com/wespot/auth/service/apple/AppleJwtParser.kt b/core/src/main/kotlin/com/wespot/auth/service/apple/AppleJwtParser.kt index fbc39b4e..f705fd89 100644 --- a/core/src/main/kotlin/com/wespot/auth/service/apple/AppleJwtParser.kt +++ b/core/src/main/kotlin/com/wespot/auth/service/apple/AppleJwtParser.kt @@ -2,6 +2,10 @@ package com.wespot.auth.service.apple import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2StreamChannelBootstrap +import org.springframework.http.HttpStatus import org.springframework.stereotype.Component import java.util.* @@ -18,7 +22,11 @@ class AppleJwtParser(private val objectMapper: ObjectMapper) { val decodedHeader = String(Base64.getUrlDecoder().decode(encodedHeader)) objectMapper.readValue(decodedHeader, object : TypeReference>() {}) } catch (e: Exception) { - throw IllegalArgumentException("Apple OAuth Identity Token 형식이 올바르지 않습니다.") + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "Apple OAuth Identity Token 형식이 올바르지 않습니다." + ) } } } diff --git a/core/src/main/kotlin/com/wespot/auth/service/apple/ApplePublicKeyGenerator.kt b/core/src/main/kotlin/com/wespot/auth/service/apple/ApplePublicKeyGenerator.kt index 1c5fc161..77540d62 100644 --- a/core/src/main/kotlin/com/wespot/auth/service/apple/ApplePublicKeyGenerator.kt +++ b/core/src/main/kotlin/com/wespot/auth/service/apple/ApplePublicKeyGenerator.kt @@ -1,6 +1,9 @@ package com.wespot.auth.service.apple import com.wespot.auth.dto.apple.ApplePublicKeysResult +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus import org.springframework.stereotype.Component import java.math.BigInteger import java.security.KeyFactory @@ -35,7 +38,11 @@ class ApplePublicKeyGenerator { val keyFactory = KeyFactory.getInstance("RSA") keyFactory.generatePublic(publicKeySpec) } catch (exception: Exception) { - throw IllegalArgumentException("Apple OAuth 로그인 중 public key 생성에 문제가 발생했습니다.", exception) + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "Apple OAuth 로그인 중 public key 생성에 문제가 발생했습니다.", + ) } } } diff --git a/core/src/main/kotlin/com/wespot/auth/service/apple/AppleService.kt b/core/src/main/kotlin/com/wespot/auth/service/apple/AppleService.kt index e7dde085..ecd793d6 100644 --- a/core/src/main/kotlin/com/wespot/auth/service/apple/AppleService.kt +++ b/core/src/main/kotlin/com/wespot/auth/service/apple/AppleService.kt @@ -5,11 +5,15 @@ import com.wespot.auth.dto.response.SocialResponse import com.wespot.auth.dto.apple.AppleRevokeRequest import com.wespot.auth.dto.apple.AppleTokenResult import com.wespot.auth.service.SocialAuthService +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.SocialType import io.jsonwebtoken.Claims import io.jsonwebtoken.Jwts import org.springframework.beans.factory.annotation.Value +import org.springframework.http.HttpStatus import org.springframework.stereotype.Service +import java.net.http.HttpRequest @Service class AppleService( @@ -28,10 +32,14 @@ class AppleService( } override fun fetchAuthToken(authLoginRequest: AuthLoginRequest): SocialResponse { - val appleId = getAppleId(authLoginRequest.identityToken - ?: throw IllegalArgumentException("Apple ID token이 없습니다.")) - val appleTokenResult = generateAuthToken(authLoginRequest.authorizationCode - ?: throw IllegalArgumentException("Authorization code가 없습니다.")) + val appleId = getAppleId( + authLoginRequest.identityToken + ?: throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "Apple ID token이 없습니다.") + ) + val appleTokenResult = generateAuthToken( + authLoginRequest.authorizationCode + ?: throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "Authorization code가 없습니다.") + ) return SocialResponse( socialId = appleId, @@ -74,12 +82,22 @@ class AppleService( AppleRevokeRequest( clientId = appleAud, clientSecret = appleCreateClientSecret.createClientSecret(), - token = socialRefreshToken ?: throw IllegalArgumentException("Refresh token is null"), + token = socialRefreshToken ?: throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "Refresh token is null" + ), tokenTypeHint = TOKEN_TYPE_HINT ) ) - require(response.status() == 200) { "Failed to revoke the token. Status: ${response.status()}" } + require(response.status() == 200) { + throw CustomException( + HttpStatus.FORBIDDEN, + ExceptionView.TOAST, + "Failed to revoke the token. Status: ${response.status()}" + ) + } return true } } diff --git a/core/src/main/kotlin/com/wespot/auth/service/kakao/KakaoService.kt b/core/src/main/kotlin/com/wespot/auth/service/kakao/KakaoService.kt index e0f2fb1a..b9eebe84 100644 --- a/core/src/main/kotlin/com/wespot/auth/service/kakao/KakaoService.kt +++ b/core/src/main/kotlin/com/wespot/auth/service/kakao/KakaoService.kt @@ -3,8 +3,11 @@ package com.wespot.auth.service.kakao import com.wespot.auth.dto.request.AuthLoginRequest import com.wespot.auth.dto.response.SocialResponse import com.wespot.auth.service.SocialAuthService +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.SocialType import org.springframework.beans.factory.annotation.Value +import org.springframework.http.HttpStatus import org.springframework.stereotype.Service @Service @@ -19,8 +22,10 @@ class KakaoService( } override fun fetchAuthToken(authLoginRequest: AuthLoginRequest): SocialResponse { - val kakaoId = getKakaoId(authLoginRequest.identityToken - ?: throw IllegalArgumentException("Kakao ID가 입력되지 않았습니다.")) + val kakaoId = getKakaoId( + authLoginRequest.identityToken + ?: throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "Kakao ID가 입력되지 않았습니다.") + ) return SocialResponse( socialId = kakaoId, @@ -44,7 +49,13 @@ class KakaoService( private fun getKakaoId(accessToken: String): String { val kakaoUserInfo = kakaoClient.getUserInfo("Bearer $accessToken") - require(kakaoUserInfo.id > 0) { "Kakao 로그인에 실패하였습니다. 사용자 정보를 가져오는 데 문제가 발생하였습니다." } + require(kakaoUserInfo.id > 0) { + CustomException( + HttpStatus.INTERNAL_SERVER_ERROR, + ExceptionView.TOAST, + "Kakao 로그인에 실패하였습니다. 사용자 정보를 가져오는 데 문제가 발생하였습니다." + ) + } return kakaoUserInfo.id.toString() } } diff --git a/core/src/main/kotlin/com/wespot/message/service/DeleteMessageService.kt b/core/src/main/kotlin/com/wespot/message/service/DeleteMessageService.kt index 0387a2ac..d7303e53 100644 --- a/core/src/main/kotlin/com/wespot/message/service/DeleteMessageService.kt +++ b/core/src/main/kotlin/com/wespot/message/service/DeleteMessageService.kt @@ -1,12 +1,15 @@ package com.wespot.message.service import com.wespot.auth.service.SecurityUtils.getLoginUser +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.message.Message import com.wespot.message.port.`in`.DeleteMessageUseCase import com.wespot.message.port.out.MessagePort import com.wespot.message.service.MessageFinder.findMessageById import com.wespot.user.User import com.wespot.user.port.out.UserPort +import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -32,7 +35,7 @@ class DeleteMessageService( return when (loginUser.id) { message.senderId -> message.sendMessageSoftDelete(loginUser) message.receiverId -> message.receivedMessageSoftDelete(loginUser) - else -> throw IllegalAccessException(NO_PERMISSION_MESSAGE) + else -> throw CustomException(HttpStatus.UNAUTHORIZED, ExceptionView.TOAST, NO_PERMISSION_MESSAGE) } } } diff --git a/core/src/main/kotlin/com/wespot/message/service/MessageFinder.kt b/core/src/main/kotlin/com/wespot/message/service/MessageFinder.kt index a3a22ca7..f096ccf0 100644 --- a/core/src/main/kotlin/com/wespot/message/service/MessageFinder.kt +++ b/core/src/main/kotlin/com/wespot/message/service/MessageFinder.kt @@ -1,20 +1,24 @@ package com.wespot.message.service +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.message.port.out.MessagePort import com.wespot.school.port.out.SchoolPort import com.wespot.user.port.out.BlockedUserPort import com.wespot.user.port.out.UserPort +import feign.FeignException.NotFound +import org.springframework.http.HttpStatus object MessageFinder { fun findMessageById(id: Long, messagePort: MessagePort) = messagePort.findById(id) - ?: throw NoSuchElementException("메시지를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "메시지를 찾을 수 없습니다.") fun findUserById(id: Long, userPort: UserPort) = userPort.findById(id) - ?: throw NoSuchElementException("유저를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "유저를 찾을 수 없습니다.") fun findSchoolById(schoolId: Long, schoolPort: SchoolPort) = schoolPort.findById(schoolId) - ?: throw NoSuchElementException("학교를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "학교를 찾을 수 없습니다.") fun findAllByBlockerId(blockerId: Long, blockedUserPort: BlockedUserPort) = blockedUserPort.findAllByBlockerId(blockerId) diff --git a/core/src/main/kotlin/com/wespot/message/service/MessageSendValidator.kt b/core/src/main/kotlin/com/wespot/message/service/MessageSendValidator.kt index d426976f..e25a29c7 100644 --- a/core/src/main/kotlin/com/wespot/message/service/MessageSendValidator.kt +++ b/core/src/main/kotlin/com/wespot/message/service/MessageSendValidator.kt @@ -1,14 +1,24 @@ package com.wespot.message.service +import com.google.common.io.ByteArrayDataInput +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.message.port.out.MessagePort import com.wespot.user.User import com.wespot.user.port.out.BlockedUserPort +import org.springframework.http.HttpStatus object MessageSendValidator { fun validateSendMessageLimit(user: User, messagePort: MessagePort): Int { val sendMessageCount = messagePort.sendMessageCount(user.id) - require(sendMessageCount < 3) { "하루에 3개까지 작성 가능해요" } + require(sendMessageCount < 3) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "하루에 3개까지 작성 가능해요" + ) + } return sendMessageCount } @@ -17,12 +27,20 @@ object MessageSendValidator { receiverId: Long, messagePort: MessagePort ) { - require(!messagePort.hasSentMessageToday(senderId, receiverId)) { "오늘 이미 해당 수신자에게 메시지를 보냈습니다." } + require(!messagePort.hasSentMessageToday(senderId, receiverId)) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "오늘 이미 해당 수신자에게 메시지를 보냈습니다." + ) + } } fun validateUserBlockStatus(senderId: Long, receiverId: Long, blockedUserPort: BlockedUserPort) { - check(!blockedUserPort.existsByBlockerIdAndBlockedId(blockerId = senderId, blockedId = receiverId) && - !blockedUserPort.existsByBlockerIdAndBlockedId(blockerId = receiverId, blockedId = senderId)) { + check( + !blockedUserPort.existsByBlockerIdAndBlockedId(blockerId = senderId, blockedId = receiverId) && + !blockedUserPort.existsByBlockerIdAndBlockedId(blockerId = receiverId, blockedId = senderId) + ) { "차단된 유저에게 메시지를 보낼 수 없습니다." } } diff --git a/core/src/main/kotlin/com/wespot/message/service/ScheduledMessageSenderService.kt b/core/src/main/kotlin/com/wespot/message/service/ScheduledMessageSenderService.kt index 88a0fb8d..028ca484 100644 --- a/core/src/main/kotlin/com/wespot/message/service/ScheduledMessageSenderService.kt +++ b/core/src/main/kotlin/com/wespot/message/service/ScheduledMessageSenderService.kt @@ -1,5 +1,7 @@ package com.wespot.message.service +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.message.Message import com.wespot.message.event.ReceivedMessageEvent import com.wespot.message.port.`in`.SchedulerMessageUseCase @@ -7,6 +9,7 @@ import com.wespot.message.port.out.MessagePort import com.wespot.user.port.out.UserPort import com.wespot.user.service.UserFinder import org.springframework.context.ApplicationEventPublisher +import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional @@ -18,7 +21,7 @@ class ScheduledMessageSenderService( private val messagePort: MessagePort, private val userPort: UserPort, private val eventPublisher: ApplicationEventPublisher, -): SchedulerMessageUseCase { +) : SchedulerMessageUseCase { @Transactional override fun sendScheduledMessages() { @@ -47,7 +50,7 @@ class ScheduledMessageSenderService( ) ) } catch (e: Exception) { - throw IllegalArgumentException("메시지 발송에 실패했습니다.${message.id}") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "메시지 발송에 실패했습니다.${message.id}") } } } diff --git a/core/src/main/kotlin/com/wespot/notification/service/NotificationFinder.kt b/core/src/main/kotlin/com/wespot/notification/service/NotificationFinder.kt index 9200ac49..3c0dd44d 100644 --- a/core/src/main/kotlin/com/wespot/notification/service/NotificationFinder.kt +++ b/core/src/main/kotlin/com/wespot/notification/service/NotificationFinder.kt @@ -1,7 +1,10 @@ package com.wespot.notification.service +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.notification.Notification import com.wespot.notification.port.out.NotificationPort +import org.springframework.http.HttpStatus import java.time.LocalDate object NotificationFinder { @@ -12,7 +15,7 @@ object NotificationFinder { fun findById(notificationPort: NotificationPort, id: Long): Notification { return notificationPort.findById(id) - ?: throw IllegalArgumentException("ID에 해당하는 알림이 없습니다.") + ?: throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "ID에 해당하는 알림이 없습니다.") } fun findAllByUserIdOrderByCreatedAtDesc( diff --git a/core/src/main/kotlin/com/wespot/report/service/SavedReportService.kt b/core/src/main/kotlin/com/wespot/report/service/SavedReportService.kt index c163d434..87ad4761 100644 --- a/core/src/main/kotlin/com/wespot/report/service/SavedReportService.kt +++ b/core/src/main/kotlin/com/wespot/report/service/SavedReportService.kt @@ -1,6 +1,9 @@ package com.wespot.report.service +import com.google.common.io.ByteArrayDataInput import com.wespot.auth.service.SecurityUtils +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.message.port.out.MessagePort import com.wespot.report.Report import com.wespot.report.ReportType @@ -12,6 +15,7 @@ import com.wespot.report.port.out.ReportPort import com.wespot.user.User import com.wespot.user.port.out.RestrictionPort import com.wespot.user.port.out.UserPort +import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -30,14 +34,14 @@ class SavedReportService( val targetUser = findTargetUserByReportRequest(loginUser, reportRequest.targetId, reportRequest.reportType) val report = Report.of(reportRequest.reportType, reportRequest.targetId, loginUser, targetUser) val reports = findAllUserReportByReportType(targetUser, reportRequest.reportType) - val savedReport = executeReport(report = report, sender = loginUser, receiver = targetUser, reports = reports) + val savedReport = executeReport(report = report, receiver = targetUser, reports = reports) return ReportResponse(savedReport.id) } private fun findLoginUser(): User { return userPort.findById(SecurityUtils.getLoginUserId(userPort)) - ?: throw NoSuchElementException("신고자가 로그인하지 않았습니다.") + ?: throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "신고자가 로그인하지 않았습니다.") } private fun findTargetUserByReportRequest(loginUser: User, targetId: Long, reportType: ReportType): User { @@ -46,7 +50,7 @@ class SavedReportService( } val message = messagePort.findById(targetId) - ?: throw NoSuchElementException("신고하고자 하는 쪽지가 존재하지 않습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "신고하고자 하는 쪽지가 존재하지 않습니다.") validateReceiverId(loginUser.id, message.receiverId) return findTargetUserByUserId(message.senderId) @@ -54,11 +58,17 @@ class SavedReportService( private fun findTargetUserByUserId(userId: Long): User { return userPort.findById(userId) - ?: throw NoSuchElementException("신고하고자 하는 사용자가 존재하지 않습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "신고하고자 하는 사용자가 존재하지 않습니다.") } private fun validateReceiverId(loginUserId: Long, receiverId: Long) { - require(loginUserId == receiverId) { "본인이 받은 쪽지가 아닙니다." } + require(loginUserId == receiverId) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "본인이 받은 쪽지가 아닙니다." + ) + } } private fun findAllUserReportByReportType(targetUser: User, reportType: ReportType): List { @@ -67,12 +77,9 @@ class SavedReportService( private fun executeReport( report: Report, - sender: User, receiver: User, reports: List ): Report { - validateReport(sender, receiver) - deleteIfMessageReport(report) val restriction = restrictionService.calculateRestrictionByReports(receiver.restriction, report, reports) receiver.restrict(restriction) @@ -83,20 +90,16 @@ class SavedReportService( return reportPort.save(report) } - private fun validateReport(sender: User, receiver: User) { - if (sender.isClassmate(receiver)) { - return - } - - throw IllegalArgumentException("같은 반 친구가 아닙니다.") - } - private fun deleteIfMessageReport(report: Report) { if (report.isVoteReport()) { return } - val message = messagePort.findById(report.targetId) ?: throw IllegalArgumentException("존재하지 않는 쪽지입니다.") + val message = messagePort.findById(report.targetId) ?: throw CustomException( + HttpStatus.NOT_FOUND, + ExceptionView.TOAST, + "존재하지 않는 쪽지입니다." + ) val reportedMessage = message.reported(report.senderId) messagePort.save(reportedMessage) } diff --git a/core/src/main/kotlin/com/wespot/user/service/SearchUserService.kt b/core/src/main/kotlin/com/wespot/user/service/SearchUserService.kt index 808c881e..0e66c51d 100644 --- a/core/src/main/kotlin/com/wespot/user/service/SearchUserService.kt +++ b/core/src/main/kotlin/com/wespot/user/service/SearchUserService.kt @@ -1,5 +1,7 @@ package com.wespot.user.service +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.school.School import com.wespot.school.SchoolType import com.wespot.school.port.out.SchoolPort @@ -12,6 +14,7 @@ import com.wespot.user.port.out.UserPort import org.springframework.data.domain.PageRequest import org.springframework.data.domain.Pageable import org.springframework.data.domain.Sort +import org.springframework.http.HttpStatus import org.springframework.stereotype.Service @Service @@ -77,9 +80,9 @@ class SearchUserService( private fun fetchCursorData(cursorId: Long): CursorSearchData { val cursorUser = userPort.findById(cursorId) - ?: throw IllegalArgumentException("사용자 정보를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "사용자 정보를 찾을 수 없습니다.") val school = cursorUser.schoolId.let { schoolPort.findById(it) } - ?: throw IllegalArgumentException("학교 정보를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "학교 정보를 찾을 수 없습니다.") val cursorSchoolTypeOrder = when (school.schoolType) { SchoolType.MIDDLE -> 1 @@ -108,7 +111,7 @@ class SearchUserService( private fun findSchool(user: User): School { return schoolPort.findById(user.schoolId) - ?: throw IllegalArgumentException("학교 정보를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "학교 정보를 찾을 수 없습니다.") } } diff --git a/core/src/main/kotlin/com/wespot/user/service/UserFinder.kt b/core/src/main/kotlin/com/wespot/user/service/UserFinder.kt index 522c2271..f0844c7d 100644 --- a/core/src/main/kotlin/com/wespot/user/service/UserFinder.kt +++ b/core/src/main/kotlin/com/wespot/user/service/UserFinder.kt @@ -1,13 +1,16 @@ package com.wespot.user.service +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.port.out.UserPort +import org.springframework.http.HttpStatus object UserFinder { fun findUserById(id: Long, userPort: UserPort) = userPort.findById(id) - ?: throw NoSuchElementException("유저를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "유저를 찾을 수 없습니다.") fun findBlockedUserById(id: Long, userPort: UserPort) = userPort.findById(id) - ?: throw NoSuchElementException("차단된 유저를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "차단된 유저를 찾을 수 없습니다.") } diff --git a/core/src/main/kotlin/com/wespot/user/service/UserService.kt b/core/src/main/kotlin/com/wespot/user/service/UserService.kt index dda8f12c..40da5bd0 100644 --- a/core/src/main/kotlin/com/wespot/user/service/UserService.kt +++ b/core/src/main/kotlin/com/wespot/user/service/UserService.kt @@ -1,6 +1,8 @@ package com.wespot.user.service import com.wespot.auth.service.SecurityUtils.getLoginUser +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.school.School import com.wespot.school.port.out.SchoolPort import com.wespot.user.User @@ -12,6 +14,7 @@ import com.wespot.user.port.out.ProfileBackgroundPort import com.wespot.user.port.out.ProfileIconPort import com.wespot.user.port.out.ProfilePort import com.wespot.user.port.out.UserPort +import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -70,6 +73,6 @@ class UserService( private fun findSchool(user: User): School { return schoolPort.findById(user.schoolId) - ?: throw IllegalArgumentException("학교 정보를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "학교 정보를 찾을 수 없습니다.") } } diff --git a/core/src/main/kotlin/com/wespot/vote/service/SavedVoteService.kt b/core/src/main/kotlin/com/wespot/vote/service/SavedVoteService.kt index 8c7a4083..87c28e0c 100644 --- a/core/src/main/kotlin/com/wespot/vote/service/SavedVoteService.kt +++ b/core/src/main/kotlin/com/wespot/vote/service/SavedVoteService.kt @@ -1,5 +1,7 @@ package com.wespot.vote.service +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User import com.wespot.user.port.out.UserPort import com.wespot.vote.Vote @@ -13,6 +15,7 @@ import com.wespot.vote.port.`in`.SavedVoteUseCase import com.wespot.vote.port.out.VotePort import com.wespot.vote.service.helper.VoteServiceHelper import org.springframework.context.ApplicationEventPublisher +import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.time.LocalDate @@ -75,7 +78,7 @@ class SavedVoteService( private fun validateRequestsSize(requestsSize: Int) { if (5 < requestsSize) { - throw IllegalArgumentException("투표는 한번에 최대 5명에게 할 수 있습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "투표는 한번에 최대 5명에게 할 수 있습니다.") } } @@ -88,7 +91,7 @@ class SavedVoteService( if (foundUserIds.size == userIds.size) { return } - throw IllegalArgumentException("투표하고자 하는 회원이 존재하지 않습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "투표하고자 하는 회원이 존재하지 않습니다.") } } diff --git a/core/src/main/kotlin/com/wespot/vote/service/helper/VoteServiceHelper.kt b/core/src/main/kotlin/com/wespot/vote/service/helper/VoteServiceHelper.kt index 2737d0b7..2700f2ac 100644 --- a/core/src/main/kotlin/com/wespot/vote/service/helper/VoteServiceHelper.kt +++ b/core/src/main/kotlin/com/wespot/vote/service/helper/VoteServiceHelper.kt @@ -1,12 +1,15 @@ package com.wespot.vote.service.helper import com.wespot.auth.service.SecurityUtils +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User import com.wespot.user.port.out.UserPort import com.wespot.vote.Vote import com.wespot.vote.port.out.VoteOptionPort import com.wespot.vote.port.out.VotePort import com.wespot.voteoption.VoteOption +import org.springframework.http.HttpStatus import java.time.LocalDate object VoteServiceHelper { @@ -17,7 +20,7 @@ object VoteServiceHelper { fun findUser(userPort: UserPort, userId: Long): User { return userPort.findById(userId) - ?: throw IllegalArgumentException("ID에 해당하는 사용자가 존재하지 않습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "ID에 해당하는 사용자가 존재하지 않습니다.") } fun findClassmatesByUser(userPort: UserPort, user: User): List { @@ -34,12 +37,12 @@ object VoteServiceHelper { grade = user.grade, classNumber = user.classNumber, date = date - ) ?: throw IllegalArgumentException("해당 투표가 존재하지 않습니다.") + ) ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "해당 투표가 존재하지 않습니다.") } fun findVoteOptionById(voteOptionPort: VoteOptionPort, optionId: Long): VoteOption { return voteOptionPort.findById(optionId) - ?: throw IllegalArgumentException("ID에 해당하는 선택지가 존재하지 않습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "ID에 해당하는 선택지가 존재하지 않습니다.") } fun findVotesReceiverIdOrderByDateDesc(votePort: VotePort, user: User, cursorId: Long, limit: Long): List { diff --git a/domain/src/main/kotlin/com/wespot/common/ProfanityChecker.kt b/domain/src/main/kotlin/com/wespot/common/ProfanityChecker.kt index 1843dfd4..a73e1ea3 100644 --- a/domain/src/main/kotlin/com/wespot/common/ProfanityChecker.kt +++ b/domain/src/main/kotlin/com/wespot/common/ProfanityChecker.kt @@ -1,5 +1,9 @@ package com.wespot.common +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus + object ProfanityChecker { private val replaceCharacters = listOf( @@ -53,7 +57,13 @@ object ProfanityChecker { ) fun validateContent(content: String) { - require(!checkProfanity(content)) { "비속어가 포함되어 있습니다." } + require(!checkProfanity(content)) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "비속어가 포함되어 있습니다." + ) + } } fun checkProfanity(content: String): Boolean { diff --git a/domain/src/main/kotlin/com/wespot/message/Message.kt b/domain/src/main/kotlin/com/wespot/message/Message.kt index b2f07de2..5ef97514 100644 --- a/domain/src/main/kotlin/com/wespot/message/Message.kt +++ b/domain/src/main/kotlin/com/wespot/message/Message.kt @@ -1,8 +1,11 @@ package com.wespot.message +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.message.MessageTimeValidator.validateMessageSendTime import com.wespot.message.MessageTimeValidator.validateMessageUpdateTime import com.wespot.user.User +import org.springframework.http.HttpStatus import java.time.LocalDateTime data class Message( @@ -34,7 +37,13 @@ data class Message( senderName: String ): Message { validateMessageOwner(modifier) - require(senderId != receiverId) { "본인이 메시지를 보낼 수 없습니다." } + require(senderId != receiverId) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "본인이 메시지를 보낼 수 없습니다." + ) + } validateMessageUpdateTime() val message = Message( id = id, @@ -91,39 +100,111 @@ data class Message( } fun validateMessageOwner(loginUser: User) { - require(messageType == MessageType.SENT) { "보낸 메시지만 수정이 가능합니다." } - require(senderId == loginUser.id) { "메시지 작성자만 수정할 수 있습니다." } + require(messageType == MessageType.SENT) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "보낸 메시지만 수정이 가능합니다." + ) + } + require(senderId == loginUser.id) { + throw CustomException( + HttpStatus.FORBIDDEN, + ExceptionView.TOAST, + "메시지 작성자만 수정할 수 있습니다." + ) + } } fun validateMessageReceiver() { - require(receiverId != senderId) { "본인이 메시지를 보낼 수 없습니다." } + require(receiverId != senderId) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "본인이 메시지를 보낼 수 없습니다." + ) + } } fun validateSentMessage(loginUser: User) { - require(receiverId == loginUser.id) { "본인이 받은 메시지만 읽을 수 있습니다." } - require(messageType == MessageType.RECEIVED) { "받은 메시지만 읽을 수 있습니다." } + require(receiverId == loginUser.id) { + throw CustomException( + HttpStatus.FORBIDDEN, + ExceptionView.TOAST, + "본인이 받은 메시지만 읽을 수 있습니다." + ) + } + require(messageType == MessageType.RECEIVED) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "받은 메시지만 읽을 수 있습니다." + ) + } } fun validateDeleteSendMessage(loginUser: User) { - require(senderId == loginUser.id) { "메시지를 삭제할 권한이 없습니다." } + require(senderId == loginUser.id) { + throw CustomException( + HttpStatus.FORBIDDEN, + ExceptionView.TOAST, + "메시지를 삭제할 권한이 없습니다." + ) + } } fun validateDeleteReceivedMessage(loginUser: User) { - require(receiverId == loginUser.id) { "메시지를 삭제할 권한이 없습니다." } + require(receiverId == loginUser.id) { + throw CustomException( + HttpStatus.FORBIDDEN, + ExceptionView.TOAST, + "메시지를 삭제할 권한이 없습니다." + ) + } } private fun validateReportMessage(reportSenderId: Long) { - require(receiverId == reportSenderId) { "수신자만이 메시지를 신고할 수 있습니다." } + require(receiverId == reportSenderId) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "수신자만이 메시지를 신고할 수 있습니다." + ) + } } fun validateReadMessage(loginUser: User) { - require(senderId == loginUser.id || receiverId == loginUser.id) { "메시지를 읽을 수 있는 권한이 없습니다." } + require(senderId == loginUser.id || receiverId == loginUser.id) { + throw CustomException( + HttpStatus.FORBIDDEN, + ExceptionView.TOAST, + "메시지를 읽을 수 있는 권한이 없습니다." + ) + } } fun validateReceivedMessage(loginUser: User) { - require(messageType == MessageType.RECEIVED) { "받은 메시지만 차단이 가능합니다." } - require(senderId != loginUser.id) { "받은 메시지만 차단이 가능합니다" } - require(receiverId == loginUser.id) { "받은 메시지만 차단이 가능합니다" } + require(messageType == MessageType.RECEIVED) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "받은 메시지만 차단이 가능합니다." + ) + } + require(senderId != loginUser.id) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "받은 메시지만 차단이 가능합니다" + ) + } + require(receiverId == loginUser.id) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "받은 메시지만 차단이 가능합니다" + ) + } } fun reported(senderId: Long): Message { diff --git a/domain/src/main/kotlin/com/wespot/message/MessageContent.kt b/domain/src/main/kotlin/com/wespot/message/MessageContent.kt index 483f8cec..0b73d267 100644 --- a/domain/src/main/kotlin/com/wespot/message/MessageContent.kt +++ b/domain/src/main/kotlin/com/wespot/message/MessageContent.kt @@ -1,6 +1,9 @@ package com.wespot.message import com.wespot.common.ProfanityChecker +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus data class MessageContent( val content: String @@ -13,8 +16,20 @@ data class MessageContent( } private fun validateContent(content: String) { - require(!ProfanityChecker.checkProfanity(content)) { "메시지의 내용에 비속어가 포함되어 있습니다." } - require(content.isNotBlank()) { "메시지의 내용은 필수로 존재해야합니다." } + require(!ProfanityChecker.checkProfanity(content)) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "메시지의 내용에 비속어가 포함되어 있습니다." + ) + } + require(content.isNotBlank()) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "메시지의 내용은 필수로 존재해야합니다." + ) + } } } diff --git a/domain/src/main/kotlin/com/wespot/message/MessageTimeValidator.kt b/domain/src/main/kotlin/com/wespot/message/MessageTimeValidator.kt index 2954e0c2..c977e061 100644 --- a/domain/src/main/kotlin/com/wespot/message/MessageTimeValidator.kt +++ b/domain/src/main/kotlin/com/wespot/message/MessageTimeValidator.kt @@ -1,5 +1,8 @@ package com.wespot.message +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus import java.time.Clock import java.time.LocalTime @@ -23,15 +26,21 @@ object MessageTimeValidator { fun validateMessageSendTime() { require(isValidTimeRange()) { - "이미 10시가 지나서 쪽지를 예약할 수 없어요\n" + - "아쉽지만 내일 다시 작성해보는 건 어떨까요?" + throw CustomException( + HttpStatus.BAD_REQUEST, ExceptionView.TOAST, + "이미 10시가 지나서 쪽지를 예약할 수 없어요\n" + + "아쉽지만 내일 다시 작성해보는 건 어떨까요?" + ) } } fun validateMessageUpdateTime() { require(isValidTimeRange()) { - "이미 10시가 지나서 쪽지를 수정할 수 없어요\n" + - "아쉽지만 내일 다시 작성해보는 건 어떨까요?" + throw CustomException( + HttpStatus.BAD_REQUEST, ExceptionView.TOAST, + "이미 10시가 지나서 쪽지를 수정할 수 없어요\n" + + "아쉽지만 내일 다시 작성해보는 건 어떨까요?" + ) } } } diff --git a/domain/src/main/kotlin/com/wespot/notification/ClassmateValidator.kt b/domain/src/main/kotlin/com/wespot/notification/ClassmateValidator.kt index 7fb8342c..b7c2c040 100644 --- a/domain/src/main/kotlin/com/wespot/notification/ClassmateValidator.kt +++ b/domain/src/main/kotlin/com/wespot/notification/ClassmateValidator.kt @@ -1,13 +1,22 @@ package com.wespot.notification +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User import com.wespot.user.UserClass +import org.springframework.http.HttpStatus object ClassmateValidator { fun validateContainNonClassmateUser(users: List) { val groupBy = users.groupBy { UserClass.of(it) } - require(groupBy.size == 1) { "다른 학급의 사용자가 포함되어 있습니다." } + require(groupBy.size == 1) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "다른 학급의 사용자가 포함되어 있습니다." + ) + } } } diff --git a/domain/src/main/kotlin/com/wespot/notification/Notification.kt b/domain/src/main/kotlin/com/wespot/notification/Notification.kt index 3fd87579..a7184962 100644 --- a/domain/src/main/kotlin/com/wespot/notification/Notification.kt +++ b/domain/src/main/kotlin/com/wespot/notification/Notification.kt @@ -1,5 +1,8 @@ package com.wespot.notification +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus import java.time.LocalDate import java.time.LocalDateTime @@ -49,7 +52,7 @@ data class Notification( type == NotificationType.VOTE || type == NotificationType.VOTE_RESULT || type == NotificationType.VOTE_RECEIVED - ) { "투표 관련 알림이 아닙니다." } + ) { throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "투표 관련 알림이 아닙니다.") } } fun createMessageInitialState( @@ -81,13 +84,19 @@ data class Notification( type == NotificationType.MESSAGE || type == NotificationType.MESSAGE_SENT || type == NotificationType.MESSAGE_RECEIVED - ) { "쪽지 관련 알림이 아닙니다." } + ) { throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "쪽지 관련 알림이 아닙니다.") } } } fun read(readerId: Long) { - require(readerId == userId) { "알림 수신자만 알림을 조회할 수 있습니다." } + require(readerId == userId) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "알림 수신자만 알림을 조회할 수 있습니다." + ) + } this.isRead = true this.readAt = LocalDateTime.now() } diff --git a/domain/src/main/kotlin/com/wespot/notification/NotificationFilterService.kt b/domain/src/main/kotlin/com/wespot/notification/NotificationFilterService.kt index 091401f1..9274e38d 100644 --- a/domain/src/main/kotlin/com/wespot/notification/NotificationFilterService.kt +++ b/domain/src/main/kotlin/com/wespot/notification/NotificationFilterService.kt @@ -1,6 +1,10 @@ package com.wespot.notification +import com.google.common.io.ByteArrayDataInput +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User +import org.springframework.http.HttpStatus import org.springframework.stereotype.Component @Component @@ -23,7 +27,13 @@ class NotificationFilterService { private fun validateNotificationType(notifications: List) { val notificationTypesCount = notifications.map { it.type }.toSet() - require(notificationTypesCount.size == 1) { "한번에 동일한 NotificationType만을 발송할 수 있습니다." } + require(notificationTypesCount.size == 1) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "한번에 동일한 NotificationType만을 발송할 수 있습니다." + ) + } } private fun getNotificationSettingBy( diff --git a/domain/src/main/kotlin/com/wespot/report/Report.kt b/domain/src/main/kotlin/com/wespot/report/Report.kt index 264147cd..0ecaa87f 100644 --- a/domain/src/main/kotlin/com/wespot/report/Report.kt +++ b/domain/src/main/kotlin/com/wespot/report/Report.kt @@ -1,6 +1,10 @@ package com.wespot.report +import com.google.common.io.ByteArrayDataInput +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User +import org.springframework.http.HttpStatus import java.time.LocalDateTime data class Report( @@ -33,7 +37,7 @@ data class Report( private fun validate(sender: User, receiver: User) { if (sender.id == receiver.id) { - throw IllegalArgumentException("본인이 본인을 신고할 수 없습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "본인이 본인을 신고할 수 없습니다.") } } diff --git a/domain/src/main/kotlin/com/wespot/report/RestrictionService.kt b/domain/src/main/kotlin/com/wespot/report/RestrictionService.kt index 039c9861..9a9dbf9a 100644 --- a/domain/src/main/kotlin/com/wespot/report/RestrictionService.kt +++ b/domain/src/main/kotlin/com/wespot/report/RestrictionService.kt @@ -1,7 +1,10 @@ package com.wespot.report +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.RestrictionType import com.wespot.user.restriction.Restriction +import org.springframework.http.HttpStatus import org.springframework.stereotype.Component @Component @@ -36,7 +39,7 @@ class RestrictionService { return } - throw IllegalArgumentException("새로 들어온 신고의 타입과 동일한 신고들을 다루어야합니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "새로 들어온 신고의 타입과 동일한 신고들을 다루어야합니다.") } private fun isSameReportType( @@ -52,7 +55,7 @@ class RestrictionService { originRestriction: Restriction ): Restriction { if (validateDuplicateReport(previousReports, newReport)) { - throw IllegalArgumentException("쪽지 하나를 여러 번 신고할 수 없습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "쪽지 하나를 여러 번 신고할 수 없습니다.") } val reportsCount = previousReports.size + 1 if (reportsCount == FIRST_MESSAGE_USAGE_RESTRICTION_COUNT) { diff --git a/domain/src/main/kotlin/com/wespot/user/UserIntroduction.kt b/domain/src/main/kotlin/com/wespot/user/UserIntroduction.kt index 10ef34c9..31592845 100644 --- a/domain/src/main/kotlin/com/wespot/user/UserIntroduction.kt +++ b/domain/src/main/kotlin/com/wespot/user/UserIntroduction.kt @@ -1,6 +1,9 @@ package com.wespot.user import com.wespot.common.ProfanityChecker +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus data class UserIntroduction( val introduction: String @@ -18,7 +21,13 @@ data class UserIntroduction( } private fun validateUserIntroduction(content: String) { - require(!ProfanityChecker.checkProfanity(content)) { "소개에 비속어가 포함되어 있습니다." } + require(!ProfanityChecker.checkProfanity(content)) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "소개에 비속어가 포함되어 있습니다." + ) + } } } diff --git a/domain/src/main/kotlin/com/wespot/user/block/BlockedUser.kt b/domain/src/main/kotlin/com/wespot/user/block/BlockedUser.kt index 6e4f9a0a..04ee3939 100644 --- a/domain/src/main/kotlin/com/wespot/user/block/BlockedUser.kt +++ b/domain/src/main/kotlin/com/wespot/user/block/BlockedUser.kt @@ -1,5 +1,8 @@ package com.wespot.user.block +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus import java.time.LocalDateTime data class BlockedUser( @@ -8,7 +11,7 @@ data class BlockedUser( val blockedId: Long, val messageId: Long, val createdAt: LocalDateTime -){ +) { companion object { fun create( @@ -16,8 +19,14 @@ data class BlockedUser( blockedId: Long, messageId: Long, isAlreadyBlocked: Boolean - ): BlockedUser{ - check(!isAlreadyBlocked) { "이미 차단된 사용자입니다." } + ): BlockedUser { + check(!isAlreadyBlocked) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "이미 차단된 사용자입니다." + ) + } return BlockedUser( id = 0, blockerId = blockerId, diff --git a/domain/src/main/kotlin/com/wespot/user/restriction/MessageRestriction.kt b/domain/src/main/kotlin/com/wespot/user/restriction/MessageRestriction.kt index 84f24db8..29844f4c 100644 --- a/domain/src/main/kotlin/com/wespot/user/restriction/MessageRestriction.kt +++ b/domain/src/main/kotlin/com/wespot/user/restriction/MessageRestriction.kt @@ -1,6 +1,9 @@ package com.wespot.user.restriction +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.RestrictionType +import org.springframework.http.HttpStatus import java.time.LocalDate data class MessageRestriction( @@ -32,12 +35,24 @@ data class MessageRestriction( } private fun validate(restrictionType: RestrictionType, restrictionDay: Long) { - require(restrictionType.isMessageRestriction()) { "쪽지로 인한 제재 타입을 입력해주세요." } + require(restrictionType.isMessageRestriction()) { + throw CustomException( + HttpStatus.INTERNAL_SERVER_ERROR, + ExceptionView.TOAST, + "쪽지로 인한 제재 타입을 입력해주세요." + ) + } require( (restrictionType == RestrictionType.PERMANENT_BAN_MESSAGE_REPORT && restrictionDay == PERMANENT_BAN_DAY) || (restrictionType == RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT && restrictionDay == FIRST_MESSAGE_USAGE_RESTRICTION_DAY) || (restrictionType == RestrictionType.TEMPORARY_BAN_MESSAGE_REPORT && restrictionDay == SECOND_MESSAGE_USAGE_RESTRICTION_DAY) - ) { "올바르지 않은 제재 타입과 제재 일 수 입니다." } + ) { + throw CustomException( + HttpStatus.INTERNAL_SERVER_ERROR, + ExceptionView.TOAST, + "올바르지 않은 제재 타입과 제재 일 수 입니다." + ) + } } } diff --git a/domain/src/main/kotlin/com/wespot/user/restriction/Restriction.kt b/domain/src/main/kotlin/com/wespot/user/restriction/Restriction.kt index e0884f78..27491b19 100644 --- a/domain/src/main/kotlin/com/wespot/user/restriction/Restriction.kt +++ b/domain/src/main/kotlin/com/wespot/user/restriction/Restriction.kt @@ -1,6 +1,9 @@ package com.wespot.user.restriction +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.RestrictionType +import org.springframework.http.HttpStatus import java.time.LocalDate data class Restriction( @@ -39,7 +42,13 @@ data class Restriction( } private fun validate(restrictionType: RestrictionType) { - require(restrictionType.isVoteRestriction() || restrictionType.isMessageRestriction()) { "RestrictionType.NONE을 추가할 수 없습니다." } + require(restrictionType.isVoteRestriction() || restrictionType.isMessageRestriction()) { + throw CustomException( + HttpStatus.INTERNAL_SERVER_ERROR, + ExceptionView.TOAST, + "RestrictionType.NONE을 추가할 수 없습니다." + ) + } } diff --git a/domain/src/main/kotlin/com/wespot/user/restriction/VoteRestriction.kt b/domain/src/main/kotlin/com/wespot/user/restriction/VoteRestriction.kt index 758e0f27..ad2187ec 100644 --- a/domain/src/main/kotlin/com/wespot/user/restriction/VoteRestriction.kt +++ b/domain/src/main/kotlin/com/wespot/user/restriction/VoteRestriction.kt @@ -1,6 +1,9 @@ package com.wespot.user.restriction +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.RestrictionType +import org.springframework.http.HttpStatus import java.time.LocalDate data class VoteRestriction( @@ -25,10 +28,22 @@ data class VoteRestriction( } private fun validate(restrictionType: RestrictionType, restrictionDay: Long) { - require(restrictionType.isVoteRestriction()) { "투표로 인한 제재 타입을 입력해주세요." } + require(restrictionType.isVoteRestriction()) { + throw CustomException( + HttpStatus.INTERNAL_SERVER_ERROR, + ExceptionView.TOAST, + "투표로 인한 제재 타입을 입력해주세요." + ) + } require( restrictionType == RestrictionType.PERMANENT_BAN_VOTE_REPORT && restrictionDay == PERMANENT_BAN_DAY - ) { "올바르지 않은 제재 타입과 제재 일 수 입니다." } + ) { + throw CustomException( + HttpStatus.INTERNAL_SERVER_ERROR, + ExceptionView.TOAST, + "올바르지 않은 제재 타입과 제재 일 수 입니다." + ) + } } } diff --git a/domain/src/main/kotlin/com/wespot/vote/Ballot.kt b/domain/src/main/kotlin/com/wespot/vote/Ballot.kt index 2304f770..b79ebf07 100644 --- a/domain/src/main/kotlin/com/wespot/vote/Ballot.kt +++ b/domain/src/main/kotlin/com/wespot/vote/Ballot.kt @@ -1,5 +1,8 @@ package com.wespot.vote +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus import java.time.LocalDate import java.time.LocalDateTime import java.util.* @@ -42,24 +45,30 @@ data class Ballot( private fun validateVote(voteId: Long) { if (Objects.isNull(voteId)) { - throw IllegalArgumentException("존재하지 않는 투표함에 투표할 수 없습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "존재하지 않는 투표함에 투표할 수 없습니다.") } } private fun validateVoteOption(voteOptionId: Long) { if (Objects.isNull(voteOptionId)) { - throw IllegalArgumentException("질문지 선택은 필수 입니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "질문지 선택은 필수 입니다.") } } private fun validateSenderAndReceiver(senderId: Long, receiverId: Long) { if (senderId == receiverId) { - throw IllegalArgumentException("본인을 투표할 수 없습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "본인을 투표할 수 없습니다.") } } private fun validateVoteDateTime(voteDate: LocalDate, voteTime: LocalDateTime) { - require(voteDate == voteTime.toLocalDate()) { throw IllegalArgumentException("투표한 시각이 잘못되었습니다.") } + require(voteDate == voteTime.toLocalDate()) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "투표한 시각이 잘못되었습니다." + ) + } } } diff --git a/domain/src/main/kotlin/com/wespot/vote/Ballots.kt b/domain/src/main/kotlin/com/wespot/vote/Ballots.kt index 187e640f..f802187a 100644 --- a/domain/src/main/kotlin/com/wespot/vote/Ballots.kt +++ b/domain/src/main/kotlin/com/wespot/vote/Ballots.kt @@ -1,5 +1,8 @@ package com.wespot.vote +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus import java.util.* data class Ballots( @@ -31,7 +34,7 @@ data class Ballots( ballot: Ballot ) { if (ballots.contains(ballot.receiverId)) { - throw IllegalArgumentException("하루에 한 명의 회원에게 한 개의 투표만 할 수 있습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "하루에 한 명의 회원에게 한 개의 투표만 할 수 있습니다.") } } @@ -48,13 +51,13 @@ data class Ballots( private fun validateNull(ballot: Ballot) { if (Objects.isNull(ballot)) { - throw IllegalArgumentException("빈 투표지를 제출할 수 없습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "빈 투표지를 제출할 수 없습니다.") } } private fun validateDuplicateVote(ballot: Ballot) { if (isVoteSameClassmate(ballot)) { - throw IllegalArgumentException("하루에 한 명의 회원에게 한 개의 투표만 할 수 있습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "하루에 한 명의 회원에게 한 개의 투표만 할 수 있습니다.") } } diff --git a/domain/src/main/kotlin/com/wespot/vote/BallotsAggregator.kt b/domain/src/main/kotlin/com/wespot/vote/BallotsAggregator.kt index c031bd3c..c45a251b 100644 --- a/domain/src/main/kotlin/com/wespot/vote/BallotsAggregator.kt +++ b/domain/src/main/kotlin/com/wespot/vote/BallotsAggregator.kt @@ -1,5 +1,10 @@ package com.wespot.vote +import com.google.common.io.ByteArrayDataInput +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus + class BallotsAggregator( val ballots: List ) { @@ -8,7 +13,7 @@ class BallotsAggregator( fun of(voteOptionId: Long, ballots: List): BallotsAggregator { if (validateBallotsForVoteOption(ballots, voteOptionId)) { - throw IllegalArgumentException("서로 다른 질문지에 대한 결과가 섞였습니다.") + throw CustomException(HttpStatus.BAD_REQUEST,ExceptionView.TOAST,"서로 다른 질문지에 대한 결과가 섞였습니다.") } return BallotsAggregator(ballots) } diff --git a/domain/src/main/kotlin/com/wespot/vote/CompleteBallot.kt b/domain/src/main/kotlin/com/wespot/vote/CompleteBallot.kt index 1770fd46..8d83ec90 100644 --- a/domain/src/main/kotlin/com/wespot/vote/CompleteBallot.kt +++ b/domain/src/main/kotlin/com/wespot/vote/CompleteBallot.kt @@ -1,7 +1,10 @@ package com.wespot.vote +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User import com.wespot.voteoption.VoteOption +import org.springframework.http.HttpStatus import java.time.LocalDateTime data class CompleteBallot( @@ -43,10 +46,34 @@ data class CompleteBallot( sender: User, receiver: User ) { - require(ballot.voteId == vote.id) { "입력된 투표가 잘못되었습니다." } - require(ballot.voteOptionId == voteOption.id) { "입력된 선택지가 잘못되었습니다." } - require(ballot.senderId == sender.id) { "입력된 송신자가 잘못되었습니다." } - require(ballot.receiverId == receiver.id) { "입력된 수신자가 잘못되었습니다." } + require(ballot.voteId == vote.id) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "입력된 투표가 잘못되었습니다." + ) + } + require(ballot.voteOptionId == voteOption.id) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "입력된 선택지가 잘못되었습니다." + ) + } + require(ballot.senderId == sender.id) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "입력된 송신자가 잘못되었습니다." + ) + } + require(ballot.receiverId == receiver.id) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "입력된 수신자가 잘못되었습니다." + ) + } } } } diff --git a/domain/src/main/kotlin/com/wespot/vote/Rate.kt b/domain/src/main/kotlin/com/wespot/vote/Rate.kt index 11b602f7..9788c236 100644 --- a/domain/src/main/kotlin/com/wespot/vote/Rate.kt +++ b/domain/src/main/kotlin/com/wespot/vote/Rate.kt @@ -1,5 +1,9 @@ package com.wespot.vote +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus + data class Rate( val value: Int ) { @@ -15,7 +19,7 @@ data class Rate( if (0 < value) { return } - throw IllegalArgumentException("등수는 0 이하일 수 없습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "등수는 0 이하일 수 없습니다.") } fun createMeaningLessRate(): Rate { diff --git a/domain/src/main/kotlin/com/wespot/vote/ReceivedVoteCalculateService.kt b/domain/src/main/kotlin/com/wespot/vote/ReceivedVoteCalculateService.kt index 73e8b298..fb38d871 100644 --- a/domain/src/main/kotlin/com/wespot/vote/ReceivedVoteCalculateService.kt +++ b/domain/src/main/kotlin/com/wespot/vote/ReceivedVoteCalculateService.kt @@ -1,7 +1,10 @@ package com.wespot.vote +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User import com.wespot.voteoption.VoteOption +import org.springframework.http.HttpStatus import org.springframework.stereotype.Component @Component @@ -22,7 +25,11 @@ class ReceivedVoteCalculateService { .withIndex() .filter { it.value.userId == user.id } .map { (index, voteMetrics) -> VoteRecord.ofWithRate(user, index + 1, voteMetrics) } - .firstOrNull() ?: throw IllegalArgumentException("해당 유저는 해당 질문지에 대한 투표를 받은 기록이 없습니다.") + .firstOrNull() ?: throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "해당 유저는 해당 질문지에 대한 투표를 받은 기록이 없습니다." + ) ballotsByVoteOption.forEach { it.receiverRead() } return voteRecord diff --git a/domain/src/main/kotlin/com/wespot/vote/Vote.kt b/domain/src/main/kotlin/com/wespot/vote/Vote.kt index fa874342..42ae43c1 100644 --- a/domain/src/main/kotlin/com/wespot/vote/Vote.kt +++ b/domain/src/main/kotlin/com/wespot/vote/Vote.kt @@ -1,7 +1,10 @@ package com.wespot.vote +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User import com.wespot.voteoption.VoteOption +import org.springframework.http.HttpStatus import java.time.LocalDate import java.time.LocalDateTime import java.util.* @@ -65,7 +68,7 @@ data class Vote( return } - throw IllegalArgumentException("입력된 이전 투표가 유효하지 않습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "입력된 이전 투표가 유효하지 않습니다.") } private fun isYesterday( @@ -116,7 +119,13 @@ data class Vote( private fun validateClassmate(user: User) { val userVoteIdentifier = VoteIdentifier.of(user, voteIdentifier.date) - require(voteIdentifier.isSameClass(userVoteIdentifier)) { "다른 반의 학생이(을) 투표할 수 없습니다." } + require(voteIdentifier.isSameClass(userVoteIdentifier)) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "다른 반의 학생이(을) 투표할 수 없습니다." + ) + } } fun getBallots(): List { diff --git a/domain/src/main/kotlin/com/wespot/vote/VoteOptionsByVoteDate.kt b/domain/src/main/kotlin/com/wespot/vote/VoteOptionsByVoteDate.kt index e5278ef1..195ded63 100644 --- a/domain/src/main/kotlin/com/wespot/vote/VoteOptionsByVoteDate.kt +++ b/domain/src/main/kotlin/com/wespot/vote/VoteOptionsByVoteDate.kt @@ -1,6 +1,9 @@ package com.wespot.vote +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.voteoption.VoteOption +import org.springframework.http.HttpStatus import java.time.LocalDate data class VoteOptionsByVoteDate( @@ -33,11 +36,23 @@ data class VoteOptionsByVoteDate( } private fun validateDate(date: LocalDate) { - require(LocalDate.now() >= date) { throw IllegalArgumentException("미래의 선택지는 정할 수 없습니다.") } + require(LocalDate.now() >= date) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "미래의 선택지는 정할 수 없습니다." + ) + } } private fun validateVoteOptionsSize(allVoteOptionsSize: Int) { - require(allVoteOptionsSize >= 5) { throw IllegalArgumentException("선택지는 최소 5개 이상이어야 합니다.") } + require(allVoteOptionsSize >= 5) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "선택지는 최소 5개 이상이어야 합니다." + ) + } } private fun validateVoteOptionsSizeMultipleOf5( @@ -45,7 +60,7 @@ data class VoteOptionsByVoteDate( voteOptionIndex: Int ) { require(allVoteOptionsSize >= voteOptionIndex + NUMBER_OF_VOTE_OPTIONS) { - throw IllegalArgumentException("선택지의 개수가 5의 배수가 아닙니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "선택지의 개수가 5의 배수가 아닙니다.") } } @@ -55,7 +70,7 @@ data class VoteOptionsByVoteDate( voteOptionId: Long ) { require(voteOptionsByVoteDate.find { it.isSameVoteOption(voteOptionId) } != null) { - throw IllegalArgumentException("오늘 제공된 질문지만 선택해 투표할 수 있습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "오늘 제공된 질문지만 선택해 투표할 수 있습니다.") } } diff --git a/domain/src/main/kotlin/com/wespot/vote/VoteRecord.kt b/domain/src/main/kotlin/com/wespot/vote/VoteRecord.kt index 53ffa474..4fa667ad 100644 --- a/domain/src/main/kotlin/com/wespot/vote/VoteRecord.kt +++ b/domain/src/main/kotlin/com/wespot/vote/VoteRecord.kt @@ -1,6 +1,9 @@ package com.wespot.vote +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.user.User +import org.springframework.http.HttpStatus import java.time.LocalDateTime import java.util.* @@ -30,10 +33,10 @@ data class VoteRecord( private fun validateInvalidUser(user: User, voteMetrics: VoteMetrics) { if (Objects.isNull(user)) { - throw IllegalArgumentException("존재하지 않는 사용자에 대한 투표가 존재합니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "존재하지 않는 사용자에 대한 투표가 존재합니다.") } if (user.id != voteMetrics.userId) { - throw IllegalArgumentException("userId가 일치하지 않습니다.") + throw CustomException(HttpStatus.BAD_REQUEST, ExceptionView.TOAST, "userId가 일치하지 않습니다.") } } diff --git a/domain/src/main/kotlin/com/wespot/voteoption/VoteOptionContent.kt b/domain/src/main/kotlin/com/wespot/voteoption/VoteOptionContent.kt index 0be422d3..f7614abc 100644 --- a/domain/src/main/kotlin/com/wespot/voteoption/VoteOptionContent.kt +++ b/domain/src/main/kotlin/com/wespot/voteoption/VoteOptionContent.kt @@ -1,6 +1,9 @@ package com.wespot.voteoption import com.wespot.common.ProfanityChecker +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView +import org.springframework.http.HttpStatus data class VoteOptionContent( val content: String @@ -15,8 +18,20 @@ data class VoteOptionContent( } private fun validateContent(content: String) { - require(!ProfanityChecker.checkProfanity(content)) { "선택지의 내용에 비속어가 포함되어 있습니다." } - require(content.isNotBlank()) { "선택지의 내용은 필수로 존재해야합니다." } + require(!ProfanityChecker.checkProfanity(content)) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "선택지의 내용에 비속어가 포함되어 있습니다." + ) + } + require(content.isNotBlank()) { + throw CustomException( + HttpStatus.BAD_REQUEST, + ExceptionView.TOAST, + "선택지의 내용은 필수로 존재해야합니다." + ) + } } } diff --git a/infrastructure/mysql/src/main/kotlin/com/wespot/school/SchoolPersistentAdapter.kt b/infrastructure/mysql/src/main/kotlin/com/wespot/school/SchoolPersistentAdapter.kt index 09fc7c21..2b9e6b4a 100644 --- a/infrastructure/mysql/src/main/kotlin/com/wespot/school/SchoolPersistentAdapter.kt +++ b/infrastructure/mysql/src/main/kotlin/com/wespot/school/SchoolPersistentAdapter.kt @@ -1,14 +1,17 @@ package com.wespot.school +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.school.port.out.SchoolPort import org.springframework.data.domain.Pageable import org.springframework.data.repository.findByIdOrNull +import org.springframework.http.HttpStatus import org.springframework.stereotype.Repository @Repository class SchoolPersistentAdapter( private val schoolJpaRepository: SchoolJpaRepository -): SchoolPort { +) : SchoolPort { override fun save(school: School): School { return schoolJpaRepository.save(SchoolMapper.mapToJpaEntity(school)) @@ -18,7 +21,7 @@ class SchoolPersistentAdapter( override fun findById(id: Long): School? { return schoolJpaRepository.findByIdOrNull(id) ?.let { SchoolMapper.mapToDomainEntity(it) } - ?: throw NoSuchElementException("학교 정보를 찾을 수 없습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST, "학교 정보를 찾을 수 없습니다.") } override fun searchSchools(keyword: String, cursorId: Long, pageable: Pageable): List { diff --git a/infrastructure/mysql/src/main/kotlin/com/wespot/vote/VotePersistenceAdapter.kt b/infrastructure/mysql/src/main/kotlin/com/wespot/vote/VotePersistenceAdapter.kt index 3160f401..1d371df7 100644 --- a/infrastructure/mysql/src/main/kotlin/com/wespot/vote/VotePersistenceAdapter.kt +++ b/infrastructure/mysql/src/main/kotlin/com/wespot/vote/VotePersistenceAdapter.kt @@ -1,10 +1,13 @@ package com.wespot.vote +import com.wespot.exception.CustomException +import com.wespot.exception.ExceptionView import com.wespot.vote.port.out.VotePort import com.wespot.voteoption.VoteOption import com.wespot.voteoption.VoteOptionJpaRepository import com.wespot.voteoption.VoteOptionMapper import org.springframework.data.repository.findByIdOrNull +import org.springframework.http.HttpStatus import org.springframework.stereotype.Repository import java.time.LocalDate @@ -65,7 +68,7 @@ class VotePersistenceAdapter( private fun getVoteOption(voteOptionId: Long): VoteOption { return voteOptionJpaRepository.findByIdOrNull(voteOptionId) ?.let { VoteOptionMapper.mapToDomainEntity(it) } - ?: throw IllegalArgumentException("해당하는 ID의 질문지가 존재하지 않습니다.") + ?: throw CustomException(HttpStatus.NOT_FOUND, ExceptionView.TOAST,"해당하는 ID의 질문지가 존재하지 않습니다.") } private fun findBallotsByVote(voteId: Long): List =