Skip to content

Commit

Permalink
Merge pull request #10 from Lunawood/master
Browse files Browse the repository at this point in the history
fix(controller, response): Success 성공시 객체로 반환
  • Loading branch information
Lunawood authored Dec 5, 2024
2 parents 8a8f6c9 + f57a6cd commit 5bb3b38
Show file tree
Hide file tree
Showing 14 changed files with 175 additions and 179 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.example.server.Response;

import com.fasterxml.jackson.annotation.JsonInclude;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class BaseResponse<T> {
private final int status;
private final String message;

@JsonInclude(JsonInclude.Include.NON_NULL)
private final T data;


public static <T> BaseResponse<T> success(SuccessBase success, T data) {
return new BaseResponse<>(success.getStatus(), success.getMessage(), data);
}

public static <T> BaseResponse<T> error(ErrorBase error) {
return new BaseResponse<>(error.getStatus(), error.getMessage(), null);
}

public static <T> BaseResponse<T> error(ErrorBase error, T data) {
return new BaseResponse<>(error.getStatus(), error.getMessage(), data);
}

public static BaseResponse<Exception> error(ErrorBase error, Exception exception) {
return new BaseResponse<>(error.getStatus(), error.getMessage(), exception);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.server.Response;

import lombok.Getter;

@Getter
public class CException extends RuntimeException {
private final ErrorBase errorBase;

public CException(ErrorBase errorBase) {
super(errorBase.getMessage());
this.errorBase = errorBase;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.example.server.Response;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestControllerAdvice
public class CExceptionHandler {
@ExceptionHandler(CException.class)
protected ResponseEntity<ErrorBase> handleCustomException(CException error) {
return ResponseEntity
.status(error.getErrorBase().getStatus())
.body(error.getErrorBase());
}

// Null 값 처리
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<BaseResponse<ErrorBase>> handleNullPointerException() {
BaseResponse<ErrorBase> response = BaseResponse.error(ErrorBase.NULL_VALUE);

return ResponseEntity
.status(ErrorBase.NULL_VALUE.getStatus())
.body(response);
}

@ExceptionHandler(Exception.class)
protected ResponseEntity<BaseResponse<Exception>> handleException(Exception exception) {
BaseResponse<Exception> response = BaseResponse.error(ErrorBase.INTERNAL_SERVER_ERROR, exception);

return ResponseEntity
.status(ErrorBase.INTERNAL_SERVER_ERROR.getStatus())
.body(response);
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
package com.example.server.error;
package com.example.server.Response;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public enum ErrorCode {
// 200
SUCCESS(200, "."),

public enum ErrorBase {
// 400 에러
REGISTERED_USER(400, "이미 존재하는 유저"),
NULL_VALUE(400, "필수 변수에 NULL값 존재"),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.server.Response;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public enum SuccessBase {
SUCCESS(200, ".");

private final int status;
private final String message;
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.server.error.CErrorResponse;
import com.example.server.error.CException;
import com.example.server.error.ErrorCode;
import com.example.server.Response.BaseResponse;
import com.example.server.Response.CException;
import com.example.server.Response.ErrorBase;
import com.example.server.Response.SuccessBase;
import com.example.server.jwt.JwtTokenService;
import com.example.server.model.User;
import com.example.server.model.UserPet;
Expand All @@ -37,43 +38,39 @@ public ResponseEntity<?> home(@RequestHeader("AccessToken") String AccessToken)
// 1. RefreshToken Valid?
try {
if(jwtTokenService.validateAccessToken(AccessToken) == false) {
throw new CException(ErrorCode.INVALID_TOKEN);
throw new CException(ErrorBase.INVALID_TOKEN);
}

} catch (Exception e) {
throw new CException(ErrorCode.INVALID_TOKEN);
throw new CException(ErrorBase.INVALID_TOKEN);
}

// 2. Check userId
Long userId;
try {
userId = jwtTokenService.extractIdFromAccessToken(AccessToken);
if(invalidTokenService.existsById(userId) == false) {
throw new CException(ErrorCode.INVALID_TOKEN);
throw new CException(ErrorBase.INVALID_TOKEN);
}
} catch (Exception e) {
throw new CException(ErrorCode.INVALID_TOKEN);
throw new CException(ErrorBase.INVALID_TOKEN);
}

// 3. Get Pet Information By UserId
User user = null;
try {
user = homeService.getPetInformation(userId);
} catch (Exception e) {
throw new CException(ErrorCode.INTERNAL_SERVER_ERROR);
throw new CException(ErrorBase.INTERNAL_SERVER_ERROR);
}

if(Objects.isNull(user))
throw new CException(ErrorCode.INTERNAL_SERVER_ERROR);
throw new CException(ErrorBase.INTERNAL_SERVER_ERROR);

UserPet userPet = new UserPet(user.getPetName(), user.getPetWeight());

return ResponseEntity
.status(ErrorCode.SUCCESS.getStatus())
.body(CErrorResponse.builder()
.status(ErrorCode.SUCCESS.getStatus())
.message(userPet)
.build()
);
.status(SuccessBase.SUCCESS.getStatus())
.body(BaseResponse.success(SuccessBase.SUCCESS, userPet));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.server.error.CErrorResponse;
import com.example.server.error.CException;
import com.example.server.error.ErrorCode;
import com.example.server.Response.BaseResponse;
import com.example.server.Response.CException;
import com.example.server.Response.ErrorBase;
import com.example.server.Response.SuccessBase;
import com.example.server.jwt.JwtTokenService;
import com.example.server.model.Token;
import com.example.server.service.LoginService;
Expand All @@ -35,18 +36,18 @@ public ResponseEntity<?> login (@RequestHeader("AccessToken") String AccessToken
try {
userId = loginService.getUserIdByKakaoOpenApi(AccessToken);
} catch(Exception e) {
throw new CException(ErrorCode.KAKAO_INVALID_TOKEN);
throw new CException(ErrorBase.KAKAO_INVALID_TOKEN);
}
// 2. userId로 데이터베이스 확인
// => 데이터베이스 false : 존재하지 않는 유저(회원가입)
try {
System.out.println(loginService.getUserIdByDatabase(userId));
if(loginService.getUserIdByDatabase(userId) == false) {
throw new CException(ErrorCode.GHOST_USER);
throw new CException(ErrorBase.GHOST_USER);
}
} catch(Exception e) {
System.out.println("Here");
throw new CException(ErrorCode.GHOST_USER);
throw new CException(ErrorBase.GHOST_USER);
}

// 3. JWT AccessToken, RefreshToken 토큰 발급
Expand All @@ -58,22 +59,18 @@ public ResponseEntity<?> login (@RequestHeader("AccessToken") String AccessToken
token.setAccessToken(accessToken);
token.setRefreshToken(refreshToken);
} catch(Exception e) {
throw new CException(ErrorCode.INTERNAL_SERVER_ERROR);
throw new CException(ErrorBase.INTERNAL_SERVER_ERROR);
}

// 4. RefreshToken RandomID Database에 저장
try {
loginService.updateRandomIdByUserId(userId, randomId);
} catch(Exception e) {
throw new CException(ErrorCode.KAKAO_INVALID_TOKEN);
throw new CException(ErrorBase.KAKAO_INVALID_TOKEN);
}

return ResponseEntity
.status(ErrorCode.SUCCESS.getStatus())
.body(CErrorResponse.builder()
.status(ErrorCode.SUCCESS.getStatus())
.message(token)
.build()
);
.status(SuccessBase.SUCCESS.getStatus())
.body(BaseResponse.success(SuccessBase.SUCCESS, token));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.server.error.CErrorResponse;
import com.example.server.error.CException;
import com.example.server.error.ErrorCode;
import com.example.server.Response.BaseResponse;
import com.example.server.Response.CException;
import com.example.server.Response.ErrorBase;
import com.example.server.Response.SuccessBase;
import com.example.server.jwt.JwtTokenService;
import com.example.server.model.Token;
import com.example.server.service.RefreshTokenService;
Expand All @@ -28,10 +29,10 @@ public ResponseEntity<?> refreshAccessToken (@RequestHeader("RefreshToken") Stri
// 1. RefreshToken Valid?
try {
if(jwtTokenService.validateRefreshToken(RefreshToken) == false) {
throw new CException(ErrorCode.INVALID_TOKEN);
throw new CException(ErrorBase.INVALID_TOKEN);
}
} catch (Exception e) {
throw new CException(ErrorCode.INVALID_TOKEN);
throw new CException(ErrorBase.INVALID_TOKEN);
}

// 2. Get userId & radomId from RefreshToken
Expand All @@ -41,19 +42,19 @@ public ResponseEntity<?> refreshAccessToken (@RequestHeader("RefreshToken") Stri
userId = jwtTokenService.extractIdFromRefreshToken(RefreshToken);
randomId = jwtTokenService.extractRandomIdFromRefreshToken(RefreshToken);
} catch (Exception e) {
throw new CException(ErrorCode.INVALID_TOKEN);
throw new CException(ErrorBase.INVALID_TOKEN);
}

if(userId == null || randomId == null)
throw new CException(ErrorCode.INVALID_TOKEN);
throw new CException(ErrorBase.INVALID_TOKEN);

// 3. Check userId & radomId
try {
if(refreshTokenService.checkIdAndRandomId(userId, randomId) == false) {
throw new CException(ErrorCode.INVALID_TOKEN);
throw new CException(ErrorBase.INVALID_TOKEN);
}
} catch (Exception e) {
throw new CException(ErrorCode.INVALID_TOKEN);
throw new CException(ErrorBase.INVALID_TOKEN);
}

// 4. JWT AccessToken, RefreshToken 토큰 발급
Expand All @@ -65,22 +66,18 @@ public ResponseEntity<?> refreshAccessToken (@RequestHeader("RefreshToken") Stri
token.setAccessToken(accessToken);
token.setRefreshToken(refreshToken);
} catch(Exception e) {
throw new CException(ErrorCode.INTERNAL_SERVER_ERROR);
throw new CException(ErrorBase.INTERNAL_SERVER_ERROR);
}

// 5. RefreshToken RandomID Database에 수정
try {
refreshTokenService.updateRandomIdByUserId(userId, new_randomId);
} catch(Exception e) {
throw new CException(ErrorCode.INTERNAL_SERVER_ERROR);
throw new CException(ErrorBase.INTERNAL_SERVER_ERROR);
}

return ResponseEntity
.status(ErrorCode.SUCCESS.getStatus())
.body(CErrorResponse.builder()
.status(ErrorCode.SUCCESS.getStatus())
.message(token)
.build()
);
.status(SuccessBase.SUCCESS.getStatus())
.body(BaseResponse.success(SuccessBase.SUCCESS, token));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.server.error.CErrorResponse;
import com.example.server.error.CException;
import com.example.server.error.ErrorCode;
import com.example.server.Response.BaseResponse;
import com.example.server.Response.CException;
import com.example.server.Response.ErrorBase;
import com.example.server.Response.SuccessBase;
import com.example.server.jwt.JwtTokenService;
import com.example.server.model.Token;
import com.example.server.model.UserPet;
Expand Down Expand Up @@ -41,17 +42,17 @@ public ResponseEntity<?> register(
try {
userId = registerService.getUserIdByKakaoOpenApi(AccessToken);
} catch(Exception e) {
throw new CException(ErrorCode.KAKAO_INVALID_TOKEN);
throw new CException(ErrorBase.KAKAO_INVALID_TOKEN);
}

// 2. userId로 데이터베이스 확인
// => 데이터베이스 true : 이미 존재하는 유저(Bad Request 400)
try {
if(registerService.getUserIdByDatabase(userId) == true) {
throw new CException(ErrorCode.REGISTERED_USER);
throw new CException(ErrorBase.REGISTERED_USER);
}
} catch(Exception e) {
throw new CException(ErrorCode.REGISTERED_USER);
throw new CException(ErrorBase.REGISTERED_USER);
}

// 3. JWT AccessToken, RefreshToken 토큰 발급
Expand All @@ -63,22 +64,18 @@ public ResponseEntity<?> register(
token.setAccessToken(accessToken);
token.setRefreshToken(refreshToken);
} catch(Exception e) {
throw new CException(ErrorCode.INTERNAL_SERVER_ERROR);
throw new CException(ErrorBase.INTERNAL_SERVER_ERROR);
}

// 4. 모든 정보 저장.
try {
registerService.createUserInfo(userId, randomId, userPet.getPetName(), userPet.getPetWeight());;
} catch(Exception e) {
throw new CException(ErrorCode.INTERNAL_SERVER_ERROR);
throw new CException(ErrorBase.INTERNAL_SERVER_ERROR);
}

return ResponseEntity
.status(ErrorCode.SUCCESS.getStatus())
.body(CErrorResponse.builder()
.status(ErrorCode.SUCCESS.getStatus())
.message(token)
.build()
);
.status(SuccessBase.SUCCESS.getStatus())
.body(BaseResponse.success(SuccessBase.SUCCESS, token));
}
}
Loading

0 comments on commit 5bb3b38

Please sign in to comment.