Skip to content

Commit

Permalink
Merge pull request #10 from Tave100Shot/9-feat-error-custom-setting
Browse files Browse the repository at this point in the history
feat error custom setting Pr
  • Loading branch information
toychip authored Nov 30, 2023
2 parents b79f5d2 + c10dc68 commit fb2eca3
Show file tree
Hide file tree
Showing 7 changed files with 131 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package com.api.TaveShot.global.constant;

import static com.api.TaveShot.global.exception.ErrorType._CANT_TRANCE_INSTANCE;

import com.api.TaveShot.global.exception.ApiException;

public final class OauthConstant {

private OauthConstant() {
throw new IllegalArgumentException("인스턴스화 불가");
throw new ApiException(_CANT_TRANCE_INSTANCE);
}

public static final String ID_PATTERN = "id";
Expand Down
15 changes: 15 additions & 0 deletions src/main/java/com/api/TaveShot/global/exception/ApiException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.api.TaveShot.global.exception;

public class ApiException extends RuntimeException {

private final ErrorType errorType;

public ApiException(ErrorType errorType) {
super(errorType.getMessage());
this.errorType = errorType;
}

public ErrorType getErrorType() {
return errorType;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.api.TaveShot.global.exception;

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

@RestControllerAdvice
public class ApiExceptionHandler {

@ExceptionHandler({ApiException.class})
public ResponseEntity<ApiExceptionResponse> handleApiException(ApiException e) {
ErrorType errorType = e.getErrorType();
ApiExceptionResponse response = new ApiExceptionResponse(
errorType.getStatus().value(),
errorType.getErrorCode(),
errorType.getMessage()
);
return ResponseEntity.status(errorType.getStatus()).body(response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.api.TaveShot.global.exception;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
@AllArgsConstructor
public class ApiExceptionResponse {

private int status;

private String errorCode;

private String message;
}
62 changes: 62 additions & 0 deletions src/main/java/com/api/TaveShot/global/exception/ErrorType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.api.TaveShot.global.exception;

import static org.springframework.http.HttpStatus.*;

import lombok.Getter;
import lombok.ToString;
import org.springframework.http.HttpStatus;

@Getter
@ToString
public enum ErrorType {

/**
* Error Message Convention
*
* name : _(head) + Error Name status : HttpStatus
*
* errorCode : 400번 오류인 상황이 여러개 올텐데, 4001, 4002, 4003.. 이런식으로 설정 (해당 오류들은 MEMBER 와 관련된 400 오류들)
* ex) Member Error, Http Status Code: 400 -> MEMBER_4000
*
* message : 사람이 알아볼 수 있도록 작성
* ex) "인증이 필요합니다."
*/

// ------------------------------------------ SERVER ------------------------------------------
_CANT_TRANCE_INSTANCE(INTERNAL_SERVER_ERROR, "SERVER_5000", "상수는 인스턴스화 할 수 없습니다."),
_SERVER_USER_NOT_FOUND(INTERNAL_SERVER_ERROR, "SERVER_5001", "로그인이 성공한 소셜 로그인 유저가 DB에 존재하지 않을 수 없습니다."),


// ---------------------------------------- JWT TOKEN ----------------------------------------
_JWT_PARSING_ERROR(BAD_REQUEST, "JWT_4001", "JWT 토큰 파싱 중 오류가 발생했습니다."),
_JWT_EXPIRED(UNAUTHORIZED, "JWT_4010", "Jwt Token의 유효 기간이 만료되었습니다."),



// ------------------------------------------ USER ------------------------------------------
_USER_NOT_FOUND(NOT_FOUND, "USER_4040", "제공된 토큰으로 사용자를 찾을 수 없습니다.")

;

private final HttpStatus status;
private final String errorCode;
private final String message;

ErrorType(HttpStatus status, String errorCode, String message) {
this.status = status;
this.errorCode = errorCode;
this.message = message;
}

public HttpStatus getStatus() {
return status;
}

public String getErrorCode() {
return errorCode;
}

public String getMessage() {
return message;
}
}
11 changes: 8 additions & 3 deletions src/main/java/com/api/TaveShot/global/jwt/JwtProvider.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package com.api.TaveShot.global.jwt;

import static com.api.TaveShot.global.constant.OauthConstant.ACCESS_TOKEN_VALID_TIME;
import static com.api.TaveShot.global.exception.ErrorType._JWT_EXPIRED;
import static com.api.TaveShot.global.exception.ErrorType._JWT_PARSING_ERROR;
import static com.api.TaveShot.global.exception.ErrorType._USER_NOT_FOUND;

import com.api.TaveShot.domain.Member.repository.MemberRepository;
import com.api.TaveShot.global.exception.ApiException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
Expand Down Expand Up @@ -65,9 +69,9 @@ public void isValidToken(final String jwtToken) {
.parseClaimsJws(jwtToken);

} catch (ExpiredJwtException e) { // 어세스 토큰 만료
throw new IllegalArgumentException("Access Token expired");
throw new ApiException(_JWT_EXPIRED);
} catch (Exception e) {
throw new IllegalArgumentException("User Not Authorized");
throw new ApiException(_JWT_PARSING_ERROR);
}
}

Expand All @@ -82,7 +86,8 @@ public void getAuthenticationFromToken(final String jwtToken) {
// token 으로부터 유저 정보 확인
private void getGitLoginId(final String jwtToken) {
Long userId = Long.valueOf(getUserIdFromToken(jwtToken));
memberRepository.findById(userId).orElseThrow(() -> new RuntimeException("token 으로 Member를 찾을 수 없음"));
memberRepository.findById(userId)
.orElseThrow(() -> new ApiException(_USER_NOT_FOUND));
}

// 토큰에서 유저 아이디 얻기
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.api.TaveShot.global.oauth2;

import static com.api.TaveShot.global.constant.OauthConstant.REDIRECT_URL;
import static com.api.TaveShot.global.exception.ErrorType._SERVER_USER_NOT_FOUND;

import com.api.TaveShot.domain.Member.domain.Member;
import com.api.TaveShot.domain.Member.dto.response.AuthResponse;
import com.api.TaveShot.domain.Member.repository.MemberRepository;
import com.api.TaveShot.global.exception.ApiException;
import com.api.TaveShot.global.jwt.JwtProvider;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
Expand Down Expand Up @@ -45,7 +47,8 @@ public void onAuthenticationSuccess(final HttpServletRequest request, final Http
String mail = githubUserInfo.getMail();
String profileImageUrl = githubUserInfo.getProfileImageUrl();

Member loginMember = memberRepository.findByGitId(Long.valueOf(id)).orElseThrow(() -> new RuntimeException("해당 gitId로 회원을 찾을 수 없음"));
Member loginMember = memberRepository.findByGitId(Long.valueOf(id)).orElseThrow(
() -> new ApiException(_SERVER_USER_NOT_FOUND));
String loginMemberId = String.valueOf(loginMember.getId());

registerHeaderToken(response, loginMemberId);
Expand Down

0 comments on commit fb2eca3

Please sign in to comment.