Home > Blockchain >  @Recover is not working for custom exception
@Recover is not working for custom exception

Time:11-12

The following retry is working fine. The recover method got invoked after 3 failed tries

@Retryable(value = MyException.class)
public String getSomething(String performanceId) {
    String s = "test";
     ...
     throw new MyException("test", new RuntimeException());
     ...
    return s;
 }

@Recover
public String recover(MyException exception, String performanceId) {
     log.info("In recover method!!!!!!!!!!!!!!!!!!");
     return "test";
}

But the following recover method will not be invoked when I changed the return type. Can you please tell why and how to fix this? Thanks a lot!

@Retryable(value = MyException.class)
public MyOwnType getSomething(String performanceId) {
    MyOwnType s = new MyOwnType();
     ...
     throw new MyException("test", new RuntimeException());
     ...
    return s;
 }

@Recover
public MyOwnType recover(MyException exception, String performanceId) {
     log.info("In recover method!!!!!!!!!!!!!!!!!!");
     return new MyOwnType();
}

public class MyOwnType implements Serializable {
...
}

EDIT: I forgot to mention that I am throwing a custom exception as well

public class MyException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public MyException(String message, Throwable cause) {
        super(message, cause);
    }

}

CodePudding user response:

This works fine for me; are you sure you have @EnableRetry?

@SpringBootApplication
@EnableRetry
public class So69916559Application {

    public static void main(String[] args) {
        SpringApplication.run(So69916559Application.class, args);
    }


    @Bean
    ApplicationRunner runner(Test test) {
        return args -> {
            System.out.println(test.getSomething("foo"));
        };
    }

}

@Component
class Test {

    private static final Logger log = LoggerFactory.getLogger(Test.class);

    @Retryable(value = RuntimeException.class)
    public MyOwnType getSomething(String performanceId) {
        MyOwnType s = new MyOwnType();
        log.info("here");
        throw new RuntimeException();
    }

    @Recover
    public MyOwnType recover(RuntimeException exception, String performanceId) {
        log.info("In recover method!!!!!!!!!!!!!!!!!!");
        return new MyOwnType();
    }

}

class MyOwnType implements Serializable {

}

Result

here
here
here
In recover method!!!!!!!!!!!!!!!!!!
com.example.demo.MyOwnType@3f725306

CodePudding user response:

Problem resolved by changing the recover method to

@Recover
public MyOwnType recover(RuntimeException exception, String performanceId) {
     log.info("In recover method!!!!!!!!!!!!!!!!!!");
     return new MyOwnType();
}

Even though MyException extends RuntimeException. The recover method will not be invoked if it is expecting MyException. Not sure why

  • Related