diff --git a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java index 763442dd1..8d94a7722 100644 --- a/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java +++ b/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixCommands.java @@ -48,7 +48,7 @@ public class HystrixCommands { private final Publisher publisher; private String commandName; private String groupName; - private Publisher fallback; + private Function> fallback; private Setter setter; private HystrixCommandProperties.Setter commandProperties; private boolean eager = false; @@ -69,6 +69,11 @@ public class HystrixCommands { } public PublisherBuilder fallback(Publisher fallback) { + this.fallback = throwable -> fallback; + return this; + } + + public PublisherBuilder fallback(Function> fallback) { this.fallback = fallback; return this; } @@ -166,10 +171,10 @@ public class HystrixCommands { private static class PublisherHystrixCommand extends HystrixObservableCommand { private Publisher publisher; - private Publisher fallback; + private Function> fallback; protected PublisherHystrixCommand(Setter setter, Publisher publisher, - Publisher fallback) { + Function> fallback) { super(setter); this.publisher = publisher; this.fallback = fallback; @@ -183,7 +188,8 @@ public class HystrixCommands { @Override protected Observable resumeWithFallback() { if (this.fallback != null) { - return RxReactiveStreams.toObservable(this.fallback); + Publisher fallbackPublisher = fallback.apply(getExecutionException()); + return RxReactiveStreams.toObservable(fallbackPublisher); } return super.resumeWithFallback(); } diff --git a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java index 698ee8a24..616a4fc4d 100644 --- a/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java +++ b/spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java @@ -66,6 +66,21 @@ public class HystrixCommandsTests { .verifyComplete(); } + @Test + public void monoFallbackWithExceptionWorks() { + StepVerifier.create(HystrixCommands.from(Mono.error(new IllegalStateException())) + .commandName("failcmd") + .fallback(throwable -> { + if (throwable instanceof IllegalStateException) { + return Mono.just("specificfallback"); + } + return Mono.just("genericfallback"); + }) + .toMono()) + .expectNext("specificfallback") + .verifyComplete(); + } + @Test public void fluxWorks() { StepVerifier.create(HystrixCommands.from( Flux.just("1", "2"))