Skip to content

Instantly share code, notes, and snippets.

@ques0942
Created November 8, 2018 10:56
Show Gist options
  • Save ques0942/145ac9109023a42fe5351e5118db2b4a to your computer and use it in GitHub Desktop.
Save ques0942/145ac9109023a42fe5351e5118db2b4a to your computer and use it in GitHub Desktop.
MasculinePersonalScreencast created by anonymous - https://repl.it/repls/MasculinePersonalScreencast
package sample;
import sample.*;
public class A {
private int i = 0;
public String error(){
i++;
if (i == 1){
throw new FirstException();
} else if (i == 2){
throw new SecondException();
} else {
throw new ThirdException();
}
}
public String success(){
i++;
if (i < 5) {
throw new FirstException();
} else {
return "success";
}
}
}
package sample;
public class FirstException extends RuntimeException {
}
import java.util.function.Supplier;
import java.util.List;
import java.util.Optional;
import java.util.*;
import sample.A;
import sample.FirstException;
import sample.SecondException;
import sample.ThirdException;
class Main {
public static void main(String[] args) {
A a = new A();
try {
Optional<String> opt = retry(
a::error,
10,
new ArrayList());
} catch (Exception e){
System.out.println("throw " + e);
}
a = new A();
try {
Optional<String> opt = retry(
a::error,
10,
Arrays.asList(FirstException.class));
} catch (Exception e){
System.out.println("throw " + e);
}
a = new A();
try {
Optional<String> opt = retry(
a::error,
10,
Arrays.asList(FirstException.class, SecondException.class));
} catch (Exception e){
System.out.println("throw " + e);
}
a = new A();
try {
Optional<String> opt = retry(
a::error,
10,
Arrays.asList(
FirstException.class, SecondException.class, ThirdException.class
)
);
System.out.println("result " + opt);
} catch (Exception e){
System.out.println("throw " + e);
}
a = new A();
Optional<String> opt = retry(
a::success,
10,
Arrays.asList(FirstException.class)
);
System.out.println("result " + opt);
}
static <R> Optional<R> retry(Supplier<R> func, int retryCount, List<Class<? extends Exception>> ignoreExceptions){
for (int i = 0; i < retryCount; i++){
try {
return Optional.of(func.get());
} catch (Exception e){
System.out.println(" debug: " + e);
Optional<Class<? extends Exception>> excOpt = ignoreExceptions.stream()
.filter(ignoreException -> ignoreException.isInstance(e))
.findFirst();
if (! excOpt.isPresent()){
throw e;
}
}
}
return Optional.empty();
}
}
package sample;
public class SecondException extends RuntimeException {
}
package sample;
public class ThirdException extends RuntimeException {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment