返回 导航

SpringBoot / Cloud

hangge.com

SpringCloud - 服务容错保护组件Hystrix的使用详解4(忽略指定异常、异常获取)

作者:hangge | 2020-07-15 08:10

四、异常处理

1,忽略指定异常

(1)使用注解配置实现 Hystrix 命令时,它还支持忽略指定异常类型功能,只需要通过设置 @HystrixCommand 注解的 ignoreExceptions 参数即可。
  • HystrixCommand 实现的 run() 方法中抛出异常时,除了 HystrixBadRequestException 之外,其他异常均会被 Hystrix 认为命令执行失败并触发服务降级的处理逻辑。
  • ignoreExceptions 参数的作用是,当方法抛出了指定类型的异常时,Hystrix 会将它包装在 HystrixBadRequestException 中抛出,这样就不会触发后续的 fallback 逻辑。

(2)比如下面样例,当方法抛出 NullPointerException 时会将异常抛出,而不触发降级服务。
@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "defaultHello", ignoreExceptions = {NullPointerException.class})
    public String hello() {
        String result = restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class)
                .getBody();
        return result;
    }

    public String defaultHello() {
        return "hangge";
    }
}

2,异常获取

(1)当 Hystrix 命令因为异常(除了 HystrixBadRequestException 的异常)进入服务降级逻辑之后,我们往往需要对不同异常做针对性的处理。
(2)要实现异常的获取非常简单,只需要在 fallback 实现方法的参数中增加 Throwable e 对象的定义,这样在方法内部就可以获取触发服务降级的具体异常内容了:
@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "defaultHello")
    public String hello() {
        String result = restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class)
                .getBody();
        return result;
    }

    public String defaultHello(Throwable e) {
        System.out.println(e.getMessage());
        return "hangge";
    }
}
评论

全部评论(0)

回到顶部