Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JorgenRingen/c9fead115bba1c8241e0b2e992f436af to your computer and use it in GitHub Desktop.
Save JorgenRingen/c9fead115bba1c8241e0b2e992f436af to your computer and use it in GitHub Desktop.
Do generic error-handling by wrapping method calls in a Supplier
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class GenericErrorHandlingWithSupplier {
private static final Logger LOGGER = LoggerFactory.getLogger(GenericErrorHandlingWithSupplier.class);
public static void main(String[] args) {
// Example 1: Every caller needs to catch all relevant exceptions
try {
methodThatThrowsException();
} catch (BusinessException e) {
LOGGER.error("Specific exception catched", e);
} catch (Exception e) {
LOGGER.error("Exception catched", e);
}
// Example 2: Callers only need to care about BusinessException. Generic error-handling in "getWithErrorHandling"
getWithErrorHandling(() -> {
try {
return methodThatThrowsException();
} catch (BusinessException e) {
LOGGER.error("Specific exception catched", e);
return null;
}
});
}
public static Object methodThatThrowsException() throws BusinessException {
throw new BusinessException();
}
public static <T> T getWithErrorHandling(Supplier<T> supplier) {
try {
return supplier.get();
} catch (Exception e) {
LOGGER.error("Exception catched in generic error-handling", e);
return null;
}
}
static class BusinessException extends Exception {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment