Skip to content
Advertisement

Java – Annotation for logging Object (CustomException) instantiations?

Small Java question regarding object instantiation and logging please.

In our (way too big) project we have one particular exception MyCustomException which is thrown.

The usual code will be something like:

if (conditionNotMet()) {
    throw new MyCustomException();
try {

} catch (SomeException e) {
    throw new MyCustomException();

There are a good thousands of throws of this kind. And for all of them, we would like to add logging, something like:

if (conditionNotMet()) {
    LOGGER.error(something bad happened, throwing a new MyCustomException());
    throw new MyCustomException();
try {

} catch (SomeException e) {
    LOGGER.error(something bad happened, throwing a new MyCustomException());
    throw new MyCustomException();

As you can imagine, since we have thousands and thousands of those, we are wasting tremendous times adding the LOGGER in all the places.

I was wondering, is there some kind of annotation we can put on the MyCustomException, something like:

@LogMeWhenIamCreated
public MyCustomException(...) {
   

So we can put this annotation in only one place, and still be able to see the logs we want, without us having to go through the entire code base and the thousands of throws?

Thank you

Advertisement

Answer

I see three options here:

  1. Use AOP to handle creation of MyCustomException. Follow this answer to see how you can write the aspect for class creation. It’s also possible to write aspect for @LogMeWhenIamCreated annoptation.
  2. Use regex to find all throw new MyCustomException(); constructions and add logging before throwing. The disadvantage is obvious – a lot of changes.
  3. Add logging to the MyCustomException constructor as Rohan suggested.

The disadvantage for options 1 and 2: if you have places where you construct the exception and don’t throw it, the log message will still be added.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement