Created
August 25, 2015 14:57
-
-
Save RobertFischer/d10bed3c1934af57fc19 to your computer and use it in GitHub Desktop.
ExceptionEater with Optional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ExceptionEater { | |
private static final Logger log = //TODO Create Logger | |
public static <T> Optional<T> swallowNPE(Supplier<T> producer) { | |
try { | |
return Optional.ofNullable(supplier.get()); | |
} catch(NullPointerException npe) { | |
log.info("NullPointerException being swallowed", npe); | |
return Optional.empty(); | |
} | |
} | |
} |
If you want to be really cool, you can do this method:
public static <T,U extends T> Optional<U> applyIfNoNPE(Supplier<U> producer, Consumer<T> consumer) {
Optional<U> result = ExceptionEater.swallowNPE(producer);
result.ifPresent(consumer);
return result;
}
Then you can do this:
applyIfNoNPE(this::getPackageIsLargeSchool, userSettings::setPackageIsLargeSchool);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Then you can do this: