我有一个服务层界面,如下所示:
public interface MyService {
void save(DomainClass domainObject) throws MyServiceException;
}
我使用Hystrix来保护实现方法:
public class MyServiceImpl implements MyService {
@HystrixCommand
public void save(DomainClass domainObject) throws MyServiceException {
remoteServiceClient.persist(domainObject);
}
}
当remoteServiceClient
失败或超时时,Hystrix会抛出HystrixRuntimeException
。但我不希望服务的客户看到任何与Hystrix相关的异常(他们应该忘记服务的实现细节,对吧?)。我想抛出MyServiceException
已检查的异常。有可能吗?我应该以不同的方式构建我的实现吗?
答案 0 :(得分:0)
有人在这里问了类似的问题:Get failure exception in @HystrixCommand fallback method
所以你的案子可以实现为:
public class MyServiceImpl implements MyService {
@HystrixCommand(fallbackMethod = "saveFallback")
public void save(DomainClass domainObject) throws MyServiceException {
remoteServiceClient.persist(domainObject);
}
@HystrixCommand
void saveFallback(Throwable e) {
throw new MyServiceException();
}
}
答案 1 :(得分:0)
使用hystrix-javanica 1.5.7
错误传播在这方面得到了很大程度的调整,默认情况下异常不会被包装为HystrixRuntimeException。
更新了错误传播:
如果您已实施了回退方法,即使失败了,那么 fallback方法抛出的异常将传播给用户
//FallbackException and CommandException are user defined
@HystrixCommand(fallbackMethod = "fall")
public String getInfo(boolean fail) {
throw new CommandException("Command failed....falling back");
}
public String fall(boolean fail) {
throw new FallbackException("Fallback failed....");
}
在这种情况下,FallbackException
将被抛出。
答案 2 :(得分:0)
@Override
@HystrixCommand(
commandKey = "gateway",
threadPoolKey = "gateway",
fallbackMethod = "fallback")
public void process(final TxnLog mTxn, final Item item) {
...force timeout
}
public void fallback(final TxnLog mTxn, final Item item, final Throwable cause) {
...other code
if (cause != null && cause instanceof HystrixTimeoutException) {
throw new InHouseException(ErrorInfoFactory.externalGatewayTimeout("External system communication timeout"));
}
} catch (HystrixRuntimeException e) {
if (e.getFallbackException().getCause() instanceof InHouseException) {
InHouseException c = ((InHouseException) e.getFallbackException().getCause());
...return actual error