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

前端 未结 11 2090
说谎
说谎 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 06:52

    One option that no one seems to have mentioned yet is to use a logger that logs to an in memory buffer, and only pushes the information into the actual log target under certain circumstances (e.g., an error level message is logged).

    If you're using the JDK 1.4 logging facilities, MemoryHandler does exactly this. I'm not sure if the logging system you're using does this, but I imagine you should be able to implement your own appender/handler/whatever that does something similar.

    Also, I just want to point out that in your original example, if your concern is variable scope, you could always define a block to reduce the scope of your variable:

    {
        String myValue = null;
        try {
            myValue = someObject.getValue();
            doSomething(myValue);
        }
        catch (BadThingsHappenException bthe) {
            String pattern = "An error occurred when setting value. [value={}]";
            // note that the format method below doesn't barf on nulls
            String detail = MessageFormatter.format(pattern, myValue);
            // consider this a RuntimeException wrapper class
            throw new UnhandledException(detail, bthe);
        }
    }
    

提交回复
热议问题