Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing and logging Exceptions, a better way

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?

like image 583
James Raitsev Avatar asked Apr 30 '12 16:04

James Raitsev


People also ask

Is it a good approach to throw an exception?

The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.

Should I log exception before throwing it?

Don't Log and Throw No matter which approach you take when handling exceptions, log the exception at the same time you handle the exception. If you log the exception and then throw it, there's a chance that the exception will be logged again further up the call stack, resulting in two log events for the same error.

Why would you want to throw an exception?

Exceptions should be used for exceptional situations outside of the normal logic of a program. In the example program an out of range value is likely to be fairly common and should be dealt with using normal if-else type logic. (See the programming exercises.)


1 Answers

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!");
}
like image 161
Thomas Mueller Avatar answered Nov 15 '22 09:11

Thomas Mueller