Skip to content

Instantly share code, notes, and snippets.

@rayyildiz
Last active February 7, 2020 15:41
Show Gist options
  • Save rayyildiz/0f613bc1a50156768ac7490f64d3485e to your computer and use it in GitHub Desktop.
Save rayyildiz/0f613bc1a50156768ac7490f64d3485e to your computer and use it in GitHub Desktop.
class ApiException extends Exception {}
@FunctionalInterface
interface ServiceBlock<T> {
T call() throws ApiException;
}
@FunctionalInterface
interface ExceptionBlock<T> {
T fallback();
}
public class ExceptionHandler {
public static <T> T run(ServiceBlock<T> call, ExceptionBlock<T> exceptionBlock) {
try {
return call.call();
} catch (ApiException e) {
return exceptionBlock.fallback();
}
}
}
class AdGroup { }
class Feed { }
class AddService {
void callFunctions() {
ExceptionBlock<AdGroup> genericFallback = () -> {
System.out.println("do something generic");
return null;
};
ExceptionHandler.run(() -> null, genericFallback);
ExceptionHandler.run(() -> {
System.out.println("another block");
return null;
}, genericFallback);
ExceptionHandler.run((ServiceBlock<Boolean>) () -> null, () -> null);
ExceptionHandler.run((ServiceBlock<Feed>) () -> null, () -> null);
ExceptionHandler.run((ServiceBlock<String>) () -> null, () -> null);
ExceptionHandler.run(() -> null, () -> null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment