티스토리 뷰

저번 포스팅에서는 Feign Client를 활용해서 서비스간의 통신을 작업했습니다.

이번 포스팅에서는 조금 방향을 틀어서 예외처리를 하는 방식에 대해서 알아보도록 할게요.


#Why?

시작하기에 앞서, 그럼 왜 예외처리를 작업해줘야 할까요? 먼저 예외처리를 하지 않은 상황에서 잘못된 URL로 접속하게 된다면, 404에러와 함께 해당 URL에 접속 할 수 없다는 오류가 발생합니다. 이 같은 경우에는 전체의 값을 전달받지 못하게 됩니다. 하지만 예외처리를 통해서 해당 URL에 예외처리를 한다면, 해당 값은 제외하고 값을 전달받을 수 있습니다. 

 


#개요

기존에 작성해둔 FeignClient를 수정해 잘못된 UrlMapping할 예정입니다. 그리고 해당 내용을 통해 의도된 Exception발생시키고, 주문 정보로 제외한 회원 정보를 Return 받을 예정입니다. 


#application.yml ( User-Service )

UserService에서 Logging의 정보를 조금 변동시켜줍니다. 이렇게 해주는 이유는 

Exception을 통해 발생되는 Log를 출력하기 위해서 입니다.

logging:
   level:
      com.example.userservice.client: DEBUG

 


#UserServiceApplication

@Bean 등록을 해줍니다.

package com.example.userservice;

import feign.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.client.RestTemplate;


@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class UserserviceApplication {

   public static void main(String[] args) {
      SpringApplication.run(UserserviceApplication.class, args);
   }

   @Bean
   public BCryptPasswordEncoder passwordEncoder(){
      return new BCryptPasswordEncoder();
   }

   @Bean
   @LoadBalanced
   public RestTemplate getRestTemplate(){return new RestTemplate();}

   @Bean
   public Logger.Level feignLoggerLevel(){
      return Logger.Level.FULL;
   }
}

Logger.Level Import 시 반드시 Feign에서 Import 해주세요. 일단 여기까지 작업 된다면 Exception을 위한 작업은 끝!


#OrderServiceClient

의도된 오류를 내기 위해 @GetMapping정보에 일부러 오류값을 넣습니다.

package com.example.userservice.client;

import com.example.userservice.vo.ResponseOrder;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

/* 사용할 Service name 으로 등록해줍니다. */
@FeignClient(name="order-service")
public interface OrderServiceClient {

    /* getOrders 를 만들어주고 해당경로값을 Mapping 해줍니다.
     * userId는 가변값이기 때문에 PathVariable 으로 등록해줍니다.
     */
    @GetMapping("/order-service/{userId}/orders_trap")
    List<ResponseOrder> getOrders(@PathVariable String userId);


}

#UserServiceImpl

그럼 해당 Exception을 핸들링하기 위한 Try ~ Catch 문을 작성하려합니다.

Log를 출력할 예정이기에 @Slf4j를 반드시 등록해줍니다.

@Service
@Slf4j
public class UserServiceImpl implements UserService {


    @Override
    public UserDto getUserByUserId(String userId) {
        UserEntity userEntity = userRepository.findByUserId(userId);


        if (userEntity == null )
            throw new UsernameNotFoundException("User not found");

        UserDto userDto = new ModelMapper().map(userEntity,UserDto.class);

        String orderUrl = String.format(env.getProperty("order_service.url"),userId);

        /* Feign Client */
        /* Feign Client Exception Handler */
        List<ResponseOrder> orderList = null;
        try{
           orderList = orderServiceClient.getOrders(userId);
        }catch (FeignException ex){
            log.error(ex.getMessage());
        }
        userDto.setOrders(orderList);

        return userDto;
    }

}

현재 @GetMapping으로 인해 반드시 Catch문이 실행되는 구조이고 발생되는 에러 종류는 FeignException이므로

해당하는 내용이 log를 통해서 출력이 될 예정입니다.


#TEST

그럼 실제로 어떻게 되는지 테스트 해보려합니다.

-회원등록-

-주문등록-

-로그인-

-회원정보-

그럼 다음과 같이 주문정보는 없지만, 회원정보는 열람 할 수 있습니다! 예외처리를 통해서 404에러 페이지가 아닌,

주문정보가 누락된 정보를 확인 할 수 있습니다!

 

 

-예외처리를 안할 경우-

페이지에 접속자체가 거부됩니다. 정보 자체를 확인 할 수 없는 상황이 됩니다.


마치며..

이번 시간엔 feign에서 발생하는 에러를 Exception 처리하는 방법을 알아봤습니다.

다음 포스팅에서는 조금 더 고도화하는 작업을 진행하겠습니다.

감사합니다.

참고 강의

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%81%B4%EB%9D%BC%EC%9A%B0%EB%93%9C-%EB%A7%88%EC%9D%B4%ED%81%AC%EB%A1%9C%EC%84%9C%EB%B9%84%EC%8A%A4

 

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA) - 인프런 | 강의

Spring framework의 Spring Cloud 제품군을 이용하여 마이크로서비스 애플리케이션을 개발해 보는 과정입니다. Cloud Native Application으로써의 Spring Cloud를 어떻게 사용하는지, 구성을 어떻게 하는지에 대해

www.inflearn.com

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함