Spring Cloud - 30. Micro Service간 통신 ErrorDecoder 구현

목차

ErrorDecoder 구현

public class FeignErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
switch (response.status()) {
case 400:
break;
case 404:
if (methodKey.contains("getOrders")) {
return new ResponseStatusException(HttpStatus.valueOf(response.status())
, "User's orders is empty.");
}
break;
default:
return new Exception(response.reason());
}

return null;
}
}
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@Slf4j
public class UserServiceApplication {

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

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

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

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

@Bean
public FeignErrorDecoder getFeignErrorDecoder(){
return new FeignErrorDecoder();
}
}
token:
expiration_time: 84600000
secret: user_token_native_application_changed

gateway:
ip: 192.168.123.106

order_service:
url: http://ORDER-SERVICE/order-service/%s/orders
exception:
orders_is_empty: User's orders is empty.
@Component
@RequiredArgsConstructor
public class FeignErrorDecoder implements ErrorDecoder {
private final Environment env;

@Override
public Exception decode(String methodKey, Response response) {
switch (response.status()) {
case 400:
break;
case 404:
if (methodKey.contains("getOrders")) {
return new ResponseStatusException(HttpStatus.valueOf(response.status())
, env.getProperty("order_service.exception.orders_is_empty"));
}
break;
default:
return new Exception(response.reason());
}

return null;
}
}
Share