8.Spring-Cloud-Hystrix之异常处理

在调用服务执行HsytrixCommand实现的run()方法抛出异常时,除HystrixBadRequestException之外,其他异常都会认为是Hystrix命令执行失败并触发服务降级处理逻辑.

异常处理

当Hystrix命令因为异常(除了HystrixBadRequestException异常)进入服务降级逻辑之后,往往需要对不同的异常做针对处理,那么就要捕获异常。对于使用@HystrixCommand注解只需要在降级函数中增加Throwable  e对象的定义

/**
* HystrixBadRequestException:
* 与由HystrixCommand抛出的所有其他异常不同,这不会触发回退,也不会对失败度量进行计数,因此不会触发断路器。
* @return
*/
@HystrixCommand(fallbackMethod="helloBackMethodFirst",ignoreExceptions=HystrixBadRequestException.class)
public String  helloService() {
logger.info("start invoke service");
//URI需要使用虚拟主机名(即服务名称,而不是主机名)
//return restTemplate.getForEntity("http://service-provide/hello", String.class).getBody();
throw new RuntimeException("consumer exception");
}
/**
* 通用降级函数
* @return
*/
@HystrixCommand(fallbackMethod="helloBackMethodSecond")
public  String  helloBackMethodFirst(Throwable  e){
/*
* 一些异常判断
* if(e instanceof CheckEception){
*  }
*  if(e instanceof IllegalStateException){
*  }
*/
//此处可能是另外一个网络请求,所以也可能出现错误
return  "error1:"+e.getMessage();
}


页面返回:

           

                                                                               微信公众号: 

                                               

                                                                             JAVA程序猿成长之路

                          分享资源,记录程序猿成长点滴。专注于Java,Spring,SpringBoot,SpringCloud,分布式,微服务。

猜你喜欢

转载自www.cnblogs.com/niugang0920/p/12194890.html
今日推荐