这篇文章主要介绍了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();
- }