What is a good way to pass useful state information to an exception in Java?

前端 未结 11 1871
说谎
说谎 2021-02-04 06:23

I noticed some confusion initially with my question. I\'m not asking about how to configure a logger nor how to use a logger properly, but rather how to capture all of the infor

11条回答
  •  [愿得一人]
    2021-02-04 07:09

    Why not keep a local copy/list of all messages that would have gone to the debug log if it was enabled, and pass that to the custom exception when you throw it? Something like:

    static void logDebug(String message, List msgs) {
        msgs.add(message);
        log.debug(message);
    }
    
    //...
    
    try {
    
        List debugMsgs = new ArrayList();
    
        String myValue = someObject.getValue();
        logDebug("Value: " + myValue, debugMsgs);
        doSomething(myValue);
    
        int x = doSomething2();
        logDebug("doSomething2() returned " + x, debugMsgs);
    
    }
    catch (BadThingsHappenException bthe) {
        // at the point when the exception is caught, 
        // debugMsgs contains some or all of the messages 
        // which should have gone to the debug log
        throw new UnhandledException(bthe, debugMsgs);
    }
    

    Your exception class can make use of this List parameter when forming getMessage():

    public class UnhandledException extends Exception {
        private List debugMessages;
    
        public UnhandledException(String message, List debugMessages) {
            super(message);
            this.debugMessages = debugMessages;
        }
    
        @Override
        public String getMessage() {
            //return concatentation of super.getMessage() and debugMessages
        }
    }
    

    The usage of this would be tedious - as you'd have to declare the local variable in every single try/catch where you wanted this type of information - but it might be worth it if you have just a few critical sections of code in which you'd like to maintain this state information on an exception.

提交回复
热议问题