Throwing and logging Exceptions, a better way
error-handling, java
Solution
You could use a utility method:
public class AppException extends Exception {
public static AppException logAndThrow(Logger logger, String message) throws AppException {
AppException e = new AppException(message);
// log the stack trace as well
logger.error(message, e);
throw e;
}
}
and the use it:
if (badThingsHappen) {
AppException.logAndThrow(logger, "oh no! not again!");
}
Problem
Ultimately, i'd like to ``` if (badThingsHappen) { log the issue throw exception with description } ``` The obvious redundancy here is that often exception description and the message to be logged is (often) the same. This looks needlessly verbose ``` if (badThingsHappen) { logger.error("oh no! not again!"); throw new AppException("oh no! not again!"); } ``` Declaring temporary String feels wrong ``` if (badThingsHappen) { String m = "oh no! not again!"; logger.error(m); throw new AppException(m); } ``` Is it ok to have Exception's constructor handle the logging? Is there a better (cleaner) way?