Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor : proto 수정 및 에러 핸들링 추가 #26

Merged
merged 1 commit into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions src/main/java/com/wanted/gold/client/AuthGrpcClient.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package com.wanted.gold.client;

import com.wanted.gold.client.dto.UserResponseDto;
import com.wanted.gold.exception.*;
import com.wanted.gold.grpc.AuthRequest;
import com.wanted.gold.grpc.AuthResponse;
import com.wanted.gold.grpc.AuthServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;

@Component
public class AuthGrpcClient {
Expand All @@ -19,15 +24,22 @@ public AuthGrpcClient() {
blockingStub = AuthServiceGrpc.newBlockingStub(channel);
}

public String getUserId(String accessToken) {
public UserResponseDto getUserIdAndRole(String accessToken) {
AuthRequest request = AuthRequest.newBuilder()
.setAccessToken(accessToken)
.build();
try {
AuthResponse response = blockingStub.authCall(request);
return response.getUserId();
return new UserResponseDto(response.getUserId(), response.getRole());
} catch (StatusRuntimeException e) {
throw new RuntimeException(e.getStatus().getDescription(), e);
if(e.getStatus().getCode() == Status.Code.UNAUTHENTICATED) // 401
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, e.getStatus().getDescription());
else if(e.getStatus().getCode() == Status.Code.NOT_FOUND) // 404
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getStatus().getDescription());
else if(e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) // 400
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getStatus().getDescription());
else // 500
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getStatus().getDescription());
}
}
}
7 changes: 7 additions & 0 deletions src/main/java/com/wanted/gold/client/dto/UserResponseDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.wanted.gold.client.dto;

public record UserResponseDto(
String userId,
String role
) {
}
1 change: 1 addition & 0 deletions src/main/java/com/wanted/gold/exception/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
public enum ErrorCode {
// 기본
BAD_REQUEST(HttpStatus.BAD_REQUEST, "잘못된 요청입니다."),
UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "유효하지 않은 접근입니다."),

// 주문
QUANTITY_TOO_MANY(HttpStatus.BAD_REQUEST, "주문할 수 없는 수량입니다. 수량을 다시 확인해주세요."),
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/com/wanted/gold/exception/UnauthorizedException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.wanted.gold.exception;

public class UnauthorizedException extends BaseException {

public UnauthorizedException(ErrorCode errorCode) {
super(errorCode);
}

public UnauthorizedException(ErrorCode errorCode, String message) {
super(errorCode, message);
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package com.wanted.gold.exception.handler;

import com.wanted.gold.exception.BadRequestException;
import com.wanted.gold.exception.ConflictException;
import com.wanted.gold.exception.ErrorResponse;
import com.wanted.gold.exception.NotFoundException;
import com.wanted.gold.exception.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
Expand All @@ -18,6 +15,12 @@ public ResponseEntity<ErrorResponse> handleBadRequestException(BadRequestExcepti
.body(new ErrorResponse(e.getErrorCode(), e.getErrorCode().getMessage()));
}

@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<ErrorResponse> handleUnauthorizedException(UnauthorizedException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(new ErrorResponse(e.getErrorCode(), e.getErrorCode().getMessage()));
}

@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFoundException(NotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.wanted.gold.order.controller;

import com.wanted.gold.exception.ErrorCode;
import com.wanted.gold.exception.UnauthorizedException;
import com.wanted.gold.order.domain.Order;
import com.wanted.gold.order.domain.OrderType;
import com.wanted.gold.order.dto.CreateOrderRequestDto;
Expand All @@ -26,7 +28,7 @@ public class OrderController {
@PostMapping("")
public ResponseEntity<String> createOrder(@RequestHeader(value = "Authorization") String token, @Valid @RequestBody CreateOrderRequestDto requestDto) {
if(token == null || !token.startsWith("Bearer "))
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("유효하지 않은 접근입니다.");
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
String accessToken = token.split("Bearer ")[1];
String response = orderService.createOrder(accessToken, requestDto);
return ResponseEntity.status(HttpStatus.CREATED).body(response);
Expand Down
7 changes: 5 additions & 2 deletions src/main/java/com/wanted/gold/order/service/OrderService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.wanted.gold.order.service;

import com.wanted.gold.client.AuthGrpcClient;
import com.wanted.gold.client.dto.UserResponseDto;
import com.wanted.gold.exception.BadRequestException;
import com.wanted.gold.exception.ErrorCode;
import com.wanted.gold.exception.NotFoundException;
Expand Down Expand Up @@ -42,8 +43,10 @@ public class OrderService {
// 주문 생성
@Transactional
public String createOrder(String accessToken, CreateOrderRequestDto requestDto) {
// 액세스토큰으로 회원 식별번호 가져오기
String userIdStr = authGrpcClient.getUserId(accessToken);
// 액세스토큰으로 회원 정보 가져오기
UserResponseDto userResponseDto = authGrpcClient.getUserIdAndRole(accessToken);
// 회원 식별번호 가져오기
String userIdStr = userResponseDto.userId();
// String -> UUID 변환
UUID userId = UUID.fromString(userIdStr);
// 입력받은 금 종류로 product 찾기
Expand Down
1 change: 1 addition & 0 deletions src/main/proto/auth.proto
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ message AuthRequest {

message AuthResponse {
string userId = 1;
string role = 2;
}

service AuthService {
Expand Down