Skip to content

Instantly share code, notes, and snippets.

@RobertFischer
Created August 25, 2015 14:57
Show Gist options
  • Save RobertFischer/d10bed3c1934af57fc19 to your computer and use it in GitHub Desktop.
Save RobertFischer/d10bed3c1934af57fc19 to your computer and use it in GitHub Desktop.
ExceptionEater with Optional
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();
}
}
}
@RobertFischer
Copy link
Author

Then you can do this:

ExceptionEater.swallowNPE(this::getPackageIsLargeSchool).ifPresent(userSettings::setPackageIsLargeSchool);

@RobertFischer
Copy link
Author

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