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");
    throw new RuntimeException("consumer exception");
}

public String helloBackMethodFirst(Throwable e) {
    // 一些异常判断
    if (e instanceof RuntimeException) {
        logger.info("error");
    }
    if (e instanceof IllegalStateException) {
    }

    return "error2:" + e.getMessage();
}

三 测试

2018-08-04 17:14:56.837  INFO 14084 --- [-HelloService-1] com.didispace.web.HelloService           : start invoke service

2018-08-04 17:14:56.846  INFO 14084 --- [-HelloService-1] com.didispace.web.HelloService           : error

四 异常类型说明

https://github.com/Netflix/Hystrix/wiki/How-To-Use#ErrorPropagation

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/81413189