diff --git a/README.md b/README.md index cfbab31..596ca76 100644 --- a/README.md +++ b/README.md @@ -78,3 +78,30 @@ public class MemberServiceImpl { - **클래스 레벨**: `@Transactional(readOnly = true)` 기본 설정 - **메서드별**: 데이터 수정 시에만 `@Transactional` 개별 적용 - **설정**: `spring.jpa.open-in-view=false` (성능 최적화) + +### 4. 오류 등록 및 사용 + +#### 오류 코드 등록 + +```java +// ApiResponseCode.java +public enum ApiResponseCode { + USER_ID_DUPLICATE("400", "이미 존재하는 사용자 ID입니다."), +} +``` + +#### 오류 사용 방법 + +```java +// Service에서 예외 발생 +throw new ApiException(ApiResponseCode.USER_ID_DUPLICATE); + +// Controller에서 예외 처리 (자동) +// GlobalExceptionHandler가 ApiException을 잡아서 응답 변환 +``` + +#### 핵심 규칙 + +- **오류 코드**: `ApiResponseCode` enum에 모든 오류 정의 +- **예외 클래스**: `ApiException`으로 비즈니스 로직 예외 처리 +- **자동 처리**: `GlobalExceptionHandler`가 일관된 응답 형태로 변환 diff --git a/src/main/java/com/bio/bio_backend/domain/user/member/service/MemberServiceImpl.java b/src/main/java/com/bio/bio_backend/domain/user/member/service/MemberServiceImpl.java index 65ed12c..b40f0f4 100644 --- a/src/main/java/com/bio/bio_backend/domain/user/member/service/MemberServiceImpl.java +++ b/src/main/java/com/bio/bio_backend/domain/user/member/service/MemberServiceImpl.java @@ -6,6 +6,8 @@ import com.bio.bio_backend.domain.user.member.enums.MemberRole; import com.bio.bio_backend.domain.user.member.mapper.MemberMapper; import com.bio.bio_backend.domain.user.member.repository.MemberRepository; import com.bio.bio_backend.domain.user.member.exception.UserDuplicateException; +import com.bio.bio_backend.global.exception.ApiException; +import com.bio.bio_backend.global.utils.ApiResponseCode; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.userdetails.UserDetails; @@ -46,7 +48,7 @@ public class MemberServiceImpl implements MemberService { public MemberDto createMember(MemberDto memberDTO) { // userId 중복 체크 if (memberRepository.existsByUserId(memberDTO.getUserId())) { - throw new UserDuplicateException("User ID already exists"); + throw new ApiException(ApiResponseCode.USER_ID_DUPLICATE); } Member member = Member.builder() diff --git a/src/main/java/com/bio/bio_backend/global/exception/ApiException.java b/src/main/java/com/bio/bio_backend/global/exception/ApiException.java new file mode 100644 index 0000000..d339468 --- /dev/null +++ b/src/main/java/com/bio/bio_backend/global/exception/ApiException.java @@ -0,0 +1,24 @@ +package com.bio.bio_backend.global.exception; + +import lombok.Getter; +import com.bio.bio_backend.global.utils.ApiResponseCode; + +@Getter +public class ApiException extends RuntimeException { + private final ApiResponseCode responseCode; + + public ApiException(ApiResponseCode responseCode) { + super(responseCode.getDescription()); + this.responseCode = responseCode; + } + + public ApiException(ApiResponseCode responseCode, String message) { + super(message); + this.responseCode = responseCode; + } + + public ApiException(ApiResponseCode responseCode, Throwable cause) { + super(responseCode.getDescription(), cause); + this.responseCode = responseCode; + } +} \ No newline at end of file diff --git a/src/main/java/com/bio/bio_backend/global/exception/GlobalExceptionHandler.java b/src/main/java/com/bio/bio_backend/global/exception/GlobalExceptionHandler.java index 558197b..349e4b1 100644 --- a/src/main/java/com/bio/bio_backend/global/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/bio/bio_backend/global/exception/GlobalExceptionHandler.java @@ -6,6 +6,7 @@ import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.servlet.resource.NoResourceFoundException; import com.fasterxml.jackson.core.JsonProcessingException; @@ -73,8 +74,32 @@ public class GlobalExceptionHandler { return CustomApiResponse.fail(ApiResponseCode.JSON_PROCESSING_EXCEPTION, null); } - @ExceptionHandler(UserDuplicateException.class) - public CustomApiResponse handleUserDuplicateException(UserDuplicateException e) { - return CustomApiResponse.fail(ApiResponseCode.USER_ID_DUPLICATE, null); + @ExceptionHandler(ApiException.class) + public CustomApiResponse handleApiException(ApiException e) { + return CustomApiResponse.fail(e.getResponseCode(), null); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public CustomApiResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + // 검증 실패한 필드들의 상세 오류 정보 추출 + var errors = e.getBindingResult().getFieldErrors().stream() + .map(error -> new ValidationError(error.getField(), error.getDefaultMessage())) + .toList(); + + return CustomApiResponse.fail(ApiResponseCode.ARGUMENT_NOT_VALID, errors); + } + + // 검증 오류 상세 정보를 위한 내부 클래스 + private static class ValidationError { + private final String field; + private final String message; + + public ValidationError(String field, String message) { + this.field = field; + this.message = message; + } + + public String getField() { return field; } + public String getMessage() { return message; } } } diff --git a/src/main/java/com/bio/bio_backend/global/utils/ApiResponseCode.java b/src/main/java/com/bio/bio_backend/global/utils/ApiResponseCode.java index e819ef6..0552807 100644 --- a/src/main/java/com/bio/bio_backend/global/utils/ApiResponseCode.java +++ b/src/main/java/com/bio/bio_backend/global/utils/ApiResponseCode.java @@ -11,44 +11,30 @@ import org.springframework.http.HttpStatus; @Getter @AllArgsConstructor public enum ApiResponseCode { - - /*login & logout*/ - + // 200 OK LOGIN_SUCCESSFUL(HttpStatus.OK.value(), "Login successful"), - LOGOUT_SUCCESSFUL(HttpStatus.OK.value(), "Logout successful"), - USER_INFO_CHANGE(HttpStatus.OK.value(), "User info update successful"), - USER_DELETE_SUCCESSFUL(HttpStatus.OK.value(), "User delete is successful"), - // 401 Unauthorized - USER_NOT_FOUND(HttpStatus.UNAUTHORIZED.value(), "User not found. Authentication failed"), - - AUTHENTICATION_FAILED(HttpStatus.UNAUTHORIZED.value(), "Password is invalid"), - // 409 Conflict USER_ID_DUPLICATE(HttpStatus.CONFLICT.value(), "User ID already exists"), - /*auth*/ - // 401 Unauthorized - JWT_SIGNATURE_MISMATCH(HttpStatus.UNAUTHORIZED.value(), "JWT signature does not match. Authentication failed"), - - JWT_TOKEN_NULL(HttpStatus.UNAUTHORIZED.value(), "JWT token is null"), - - JWT_TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED.value(), "Token is Expired"), - - All_TOKEN_INVALID(HttpStatus.UNAUTHORIZED.value(), "Access and Refresh tokens are expired or invalid"), - /*공통 Code*/ // 400 Bad Request COMMON_BAD_REQUEST(HttpStatus.BAD_REQUEST.value(), "Required request body is missing or Error"), - COMMON_FORMAT_WRONG(HttpStatus.BAD_REQUEST.value(), "Request format is incorrect"), + ARGUMENT_NOT_VALID(HttpStatus.BAD_REQUEST.value(), "Argument is not valid"), // 401 Unauthorized COMMON_UNAUTHORIZED(HttpStatus.UNAUTHORIZED.value(), "Unauthorized"), + USER_NOT_FOUND(HttpStatus.UNAUTHORIZED.value(), "User not found. Authentication failed"), + AUTHENTICATION_FAILED(HttpStatus.UNAUTHORIZED.value(), "Password is invalid"), + JWT_SIGNATURE_MISMATCH(HttpStatus.UNAUTHORIZED.value(), "JWT signature does not match. Authentication failed"), + JWT_TOKEN_NULL(HttpStatus.UNAUTHORIZED.value(), "JWT token is null"), + JWT_TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED.value(), "Token is Expired"), + All_TOKEN_INVALID(HttpStatus.UNAUTHORIZED.value(), "Access and Refresh tokens are expired or invalid"), // 403 Forbidden COMMON_FORBIDDEN(HttpStatus.FORBIDDEN.value(), "Access is denied"), @@ -61,11 +47,7 @@ public enum ApiResponseCode { // 500 Internal Server Error INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An error occurred on the server"), - - ARGUMENT_NOT_VALID(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Argument is not valid"), - INDEX_OUT_OF_BOUND(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Index out of bounds for length"), - JSON_PROCESSING_EXCEPTION(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Check if it is a valid JSON format"); private final int statusCode;