diff --git a/src/main/java/com/example/UserService/controller/UserController.java b/src/main/java/com/example/UserService/controller/UserController.java index 18f17db..965fbe5 100644 --- a/src/main/java/com/example/UserService/controller/UserController.java +++ b/src/main/java/com/example/UserService/controller/UserController.java @@ -14,6 +14,7 @@ import jakarta.validation.Valid; import jakarta.validation.constraints.Email; import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -59,7 +60,7 @@ public ResponseEntity findUserResponseByUserId(@PathVariable("user return ResponseEntity.ok().body(userResponse); } catch (BusinessLogicException e) { ExceptionCode exceptionCode = e.getExceptionCode(); - int status = exceptionCode.getStatus(); + HttpStatus status = exceptionCode.getStatus(); String message = exceptionCode.getMessage(); return ResponseEntity.status(status).body(new UserResponse(message)); } @@ -72,7 +73,7 @@ public ResponseEntity findUserResponseByEmail(@PathVariable String return ResponseEntity.ok().body(userResponse); } catch (BusinessLogicException e) { ExceptionCode exceptionCode = e.getExceptionCode(); - int status = exceptionCode.getStatus(); + HttpStatus status = exceptionCode.getStatus(); String message = exceptionCode.getMessage(); return ResponseEntity.status(status).body(new UserResponse(message)); } diff --git a/src/main/java/com/example/UserService/dto/ApiResponse.java b/src/main/java/com/example/UserService/dto/ApiResponse.java new file mode 100644 index 0000000..925f28c --- /dev/null +++ b/src/main/java/com/example/UserService/dto/ApiResponse.java @@ -0,0 +1,59 @@ +package com.example.UserService.dto; + +import com.example.UserService.exception.ExceptionCode; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class ApiResponse { + + // API 상태 코드 + private int code; + + // API 상태 + private HttpStatus status; + + // API 응답 메시지 + private String message; + + // API 응답 데이터 + private T data; + + private ApiResponse(HttpStatus status, String message, T data) { + this.code = status.value(); + this.status = status; + this.message = message; + this.data = data; + } + + public static ApiResponse of(HttpStatus status, String message, T data) { + return new ApiResponse<>(status, message, data); + } + + public static ApiResponse of(HttpStatus status, T data) { + return of(status, status.name(), data); + } + + public static ApiResponse ok(T data) { + return of(HttpStatus.OK, data); + } + + public static ApiResponse ok(String message) { + return of(HttpStatus.OK, message, null); + } + + public static ApiResponse ok(String message, T data) { + return of(HttpStatus.OK, message, data); + } + + public static ApiResponse withError(ExceptionCode exceptionCode, T data) { + return new ApiResponse<>(exceptionCode.getStatus(), exceptionCode.getMessage(), data); + } + + public static ApiResponse withError(ExceptionCode exceptionCode) { + return withError(exceptionCode, null); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/UserService/exception/ExceptionCode.java b/src/main/java/com/example/UserService/exception/ExceptionCode.java index f10bc5f..3855c15 100644 --- a/src/main/java/com/example/UserService/exception/ExceptionCode.java +++ b/src/main/java/com/example/UserService/exception/ExceptionCode.java @@ -1,29 +1,26 @@ package com.example.UserService.exception; import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +@Getter +@RequiredArgsConstructor public enum ExceptionCode { - MEMBER_NOT_FOUND(404, "회원을 찾을 수 없습니다"), - RESOURCE_NOT_FOUND(404, "리소스를 찾을 수 없습니다"), - BAD_REQUEST(400, "잘못된 요청입니다"), - UNAUTHORIZED(401, "인증되지 않았습니다"), - FORBIDDEN(403, "접근이 금지되었습니다"), - INVALID_INPUT(422, "유효하지 않은 입력입니다"), - INTERNAL_SERVER_ERROR(500, "내부 서버 오류입니다"), - MEMBER_EXISTS(409, "이미 존재하는 회원입니다"), - NO_SUCH_ALGORITHM(500, "존재하지 않는 알고리즘입니다"), - UNABLE_TO_SEND_EMAIL(500, "이메일을 전송할 수 없습니다"), - TOKEN_IS_NOT_SAME(401, "액세스 토큰과 리프레시 토큰이 일치하지 않습니다"), - HEADER_REFRESH_TOKEN_NOT_EXISTS(400, "요청 헤더에 리프레시 토큰이 누락되었습니다"); + MEMBER_NOT_FOUND(HttpStatus.NOT_FOUND, "회원을 찾을 수 없습니다"), + RESOURCE_NOT_FOUND(HttpStatus.NOT_FOUND, "리소스를 찾을 수 없습니다"), + BAD_REQUEST(HttpStatus.BAD_REQUEST, "잘못된 요청입니다"), + UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "인증되지 않았습니다"), + FORBIDDEN(HttpStatus.FORBIDDEN, "접근이 금지되었습니다"), + INVALID_INPUT(HttpStatus.BAD_REQUEST, "유효하지 않은 입력입니다"), + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "내부 서버 오류입니다"), + MEMBER_EXISTS(HttpStatus.CONFLICT, "이미 존재하는 회원입니다"), + NO_SUCH_ALGORITHM(HttpStatus.INTERNAL_SERVER_ERROR, "존재하지 않는 알고리즘입니다"), + UNABLE_TO_SEND_EMAIL(HttpStatus.INTERNAL_SERVER_ERROR, "이메일을 전송할 수 없습니다"), + TOKEN_IS_NOT_SAME(HttpStatus.UNAUTHORIZED, "액세스 토큰과 리프레시 토큰이 일치하지 않습니다"), + HEADER_REFRESH_TOKEN_NOT_EXISTS(HttpStatus.BAD_REQUEST, "요청 헤더에 리프레시 토큰이 누락되었습니다"); - @Getter - private int status; + private final HttpStatus status; + private final String message; - @Getter - private String message; - - ExceptionCode(int status, String message) { - this.status = status; - this.message = message; - } } diff --git a/src/main/java/com/example/UserService/exception/GlobalExceptionHandler.java b/src/main/java/com/example/UserService/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..092bdd9 --- /dev/null +++ b/src/main/java/com/example/UserService/exception/GlobalExceptionHandler.java @@ -0,0 +1,14 @@ +package com.example.UserService.exception; + +import com.example.UserService.dto.ApiResponse; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(BlogAPIException.class) + public ApiResponse handleBlogAPIException(BlogAPIException e) { + return ApiResponse.withError(ExceptionCode.MEMBER_EXISTS); + } +} diff --git a/src/main/java/com/example/UserService/repository/UserRepository.java b/src/main/java/com/example/UserService/repository/UserRepository.java index 7dde358..e2f8734 100644 --- a/src/main/java/com/example/UserService/repository/UserRepository.java +++ b/src/main/java/com/example/UserService/repository/UserRepository.java @@ -4,11 +4,13 @@ import com.example.UserService.dto.UserResponse; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; import java.util.Optional; +@Repository public interface UserRepository extends JpaRepository { Optional findByEmail(String email); diff --git a/src/main/java/com/example/UserService/service/UserServiceImpl.java b/src/main/java/com/example/UserService/service/UserServiceImpl.java index 6df78d4..9190de3 100644 --- a/src/main/java/com/example/UserService/service/UserServiceImpl.java +++ b/src/main/java/com/example/UserService/service/UserServiceImpl.java @@ -17,6 +17,7 @@ import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; import org.modelmapper.convention.MatchingStrategies; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -80,7 +81,7 @@ public String register(RequestUser requestUser) { // add check for email exists in database if(userRepository.existsByEmail(requestUser.getEmail())){ - throw new BlogAPIException(HttpStatus.BAD_REQUEST, "Email is already exists!."); + throw new BlogAPIException(HttpStatus.BAD_REQUEST, "Email is already exists!"); } ModelMapper mapper = new ModelMapper(); @@ -91,7 +92,7 @@ public String register(RequestUser requestUser) { userEntity.setCreatedAt(LocalDate.now()); userRepository.save(userEntity); - return "User registered successfully!."; + return "User registered successfully!"; } @Override