Created
March 22, 2018 08:41
-
-
Save JorgenRingen/c9fead115bba1c8241e0b2e992f436af to your computer and use it in GitHub Desktop.
Do generic error-handling by wrapping method calls in a Supplier
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
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