spring 在@HystrixCommand 回退方法中获取失败异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32830654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:48:02  来源:igfitidea点击:

Get failure exception in @HystrixCommand fallback method

springspring-cloudhystrix

提问by Andrew Serff

Is there a way to get the reason a HystrixCommandfailed when using the @HystrixCommandannotation within a Spring Boot application? It looks like if you implement your own HystrixCommand, you have access to the getFailedExecutionExceptionbut how can you get access to this when using the annotation? I would like to be able to do different things in the fallback method based on the type of exception that occurred. Is this possible?

在 Spring Boot 应用程序中HystrixCommand使用@HystrixCommand注释时,有没有办法找出失败的原因?看起来如果您实现自己的HystrixCommand,您可以访问 ,getFailedExecutionException但是在使用注释时如何访问它?我希望能够根据发生的异常类型在回退方法中做不同的事情。这可能吗?

I saw a noteabout HystrixRequestContext.initializeContext()but the HystrixRequestContextdoesn't give you access to anything, is there a different way to use that context to get access to the exceptions?

我看到了一条关于但没有让您访问任何内容的注释,是否有其他方法可以使用该上下文来访问异常?HystrixRequestContext.initializeContext()HystrixRequestContext

采纳答案by Andrew Serff

I haven't found a way to get the exception with Annotations either, but creating my own Command worked for me like so:

我也没有找到通过注释获取异常的方法,但是创建我自己的命令对我来说是这样的:

public static class DemoCommand extends HystrixCommand<String> {

    protected DemoCommand() {
        super(HystrixCommandGroupKey.Factory.asKey("Demo"));
    }

    @Override
    protected String run() throws Exception {
        throw new RuntimeException("failed!");
    }

    @Override
    protected String getFallback() {
        System.out.println("Events (so far) in Fallback: " + getExecutionEvents());
        return getFailedExecutionException().getMessage();
    }

}

Hopefully this helps someone else as well.

希望这对其他人也有帮助。

回答by MattJ

Simply add a Throwable parameter to the fallback method and it will receive the exception which the original command produced.

只需向回退方法添加一个 Throwable 参数,它就会收到原始命令产生的异常。

From https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica

来自https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica

    @HystrixCommand(fallbackMethod = "fallback1")
    User getUserById(String id) {
        throw new RuntimeException("getUserById command failed");
    }

    @HystrixCommand(fallbackMethod = "fallback2")
    User fallback1(String id, Throwable e) {
        assert "getUserById command failed".equals(e.getMessage());
        throw new RuntimeException("fallback1 failed");
    }

回答by ákos Ratku

I couldn't find a way to obtain the exception with the annotations, but i found HystrixPlugins, with that you can register a HystrixCommandExecutionHookand you can get the exact exception in that like this :

我找不到通过注释获取异常的方法,但我发现HystrixPlugins,您可以注册 aHystrixCommandExecutionHook并且可以像这样获得确切的异常:

HystrixPlugins.getInstance().registerCommandExecutionHook(new HystrixCommandExecutionHook() {
            @Override
            public <T> void onFallbackStart(final HystrixInvokable<T> commandInstance) {

            }
        });

The command instance is a GenericCommand.

命令实例是一个GenericCommand.

回答by Seetharamani Tmr

Most of the time just using getFailedExecutionException().getMessage() gave me null values.

大多数时候只使用 getFailedExecutionException().getMessage() 给我空值。

   Exception errorFromThrowable = getExceptionFromThrowable(getExecutionException());
   String errMessage = (errorFromThrowable != null) ? errorFromThrowable.getMessage()

this gives me better results all the time.

这一直给我更好的结果。

回答by vicco

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

如文档中所述,Hystrix-documentationgetFallback()方法将在以下情况下抛出:

  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.
  1. 每当命令执行失败时:construct() 或 run() 抛出异常时
  2. 当指令因电路开路而短路时
  3. 当命令的线程池和队列或信号量已满时
  4. 当命令超过其超时长度时。

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

因此,您可以通过将执行异常分配给Throwable 对象来轻松获取引发回退方法调用的内容。

Assuming your HystrixCommand returns a String

假设你的 HystrixCommand 返回一个字符串

public class ExampleTask extends HystrixCommand<String> {
   //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

更多信息在这里