Skip to content
Advertisement

Java + Webflux + Resilience4j: Name of the method triggering the fallBack method

Small question regarding Java SpringBoot Webflux with Resilience4J (not Spring Cloud Circuit Breaker) please.

I have the following straightforward:

    @TimeLimiter(name = "methodOne", fallbackMethod = "fallbackMethod")
    public Mono<String> methodOne(@RequestParam(value = "name", defaultValue = "World") String name) {
        return WebClient.builder().baseUrl("http://localhost:8081/serviceBgreeting?name=" + name).build().get().retrieve().bodyToMono(String.class);
    }

    @TimeLimiter(name = "methodTwo", fallbackMethod = "fallbackMethod")
    public Mono<String> methodTwo(@RequestParam(value = "name", defaultValue = "World") String name) {
        return WebClient.builder().baseUrl("http://localhost:8082/anotherMethodTwo?name=" + name).build().get().retrieve().bodyToMono(String.class);
    }

And one same callee fallbackMethod, shared by all callers, as:

    public Mono<Object> fallBackMethod(Exception exception) {
        System.out.println("For debug purpose, I need to know what is the exact method falling back to this fallback method");
        return //the fallback thing needed;

What is the best way to retrieve which one of the two methods methodOne or methodTwo was actually the trigger of this fallback please?

I have some 1000+ methods with this pattern, so I cannot just create 1000+ fallback methods. (like methodOne falls to fallbackOne, methodTwo to fallbackTwo etc…, I cannot)

I am sure there is a smart way to get the method name triggering the fallback.

Tried StackWalker which gives only (fallBackMethod, invoke, fallback, lambda$reactorOnErrorResume$1, onError, etc…) But not the method triggering the fallBack.

A bit of help please.

Thank you

Advertisement

Answer

Can you try Executing this from fallbackMethod We are collecting the list of available methods in the executing call and from stack trace checking if the very recent caller is present.

Method[] methods = this.getClass().getMethods();
StackTraceElement[] stackTrace = throwable.getStackTrace();
Optional<StackTraceElement> first = Arrays.stream(stackTrace)
                .filter(s -> Arrays.stream(methods).anyMatch(m -> m.getName().equalsIgnoreCase(s.getMethodName())))
                .findFirst();
log.error("Method name Starts here");
first.ifPresent(System.out::println);
log.error("Method name Ends here");

This is printing something similar to this

in.silentsudo.webapi.services.PaymentOptionService.availablePaymentOptions(PaymentOptionService.java:36)

We can extract the method name from here.

This is how my caller looks like

@CircuitBreaker(
            name = "payment-option-service-circuit-breaker",
            fallbackMethod = "paymentOptionOnCircuitBreak"
)
public Map<String, List<PaymentOption>> availablePaymentOptions() {
...
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement