Get failure exception in @HystrixCommand fallback method

后端 未结 5 1317
-上瘾入骨i
-上瘾入骨i 2020-12-28 08:21

Is there a way to get the reason a HystrixCommand failed when using the @HystrixCommand annotation within a Spring Boot application? It looks like

5条回答
  •  Happy的楠姐
    2020-12-28 09:13

    As said in the documentation Hystrix-documentation getFallback() method will be thrown when:

    1. Whenever a command execution fails: when an exception is thrown by construct() or run()
    2. When the command is short-circuited because the circuit is open
    3. When the command’s thread pool and queue or semaphore are at capacity
    4. When the command has exceeded its timeout length.

    So you can easily get what raised your fallback method called by assigning the the execution exception to a Throwable object.

    Assuming your HystrixCommand returns a String

    public class ExampleTask extends HystrixCommand {
       //Your class body
    }
    

    do as follows:

    @Override
        protected ErrorCodes getFallback() {
            Throwable t = getExecutionException();
            if (circuitBreaker.isOpen()) {
                // Log or something
            } else if (t instanceof RejectedExecutionException) {
                // Log and get the threadpool name, could be useful
            } else {
                // Maybe something else happened
            }
            return "A default String"; // Avoid using any HTTP request or ypu will need to wrap it also in HystrixCommand
        }
    

    More info here

提交回复
热议问题