An exception that provides an easy and safe way to add contextual information.
An exception trace itself is often insufficient to provide rapid diagnosis of the issue. Frequently what is needed is a select few pieces of local contextual data. Providing this data is tricky however, due to concerns over formatting and nulls.
The contexted exception approach allows the exception to be created together with a map of context values. This additional information is automatically included in the message and printed stack trace.
An unchecked version of this exception is provided by ContextedRuntimeException.
To use this class write code as follows:
try { ... } catch (Exception e) { throw new ContextedException("Error posting account transaction", e) .addValue("accountNumber", accountNumber) .addValue("amountPosted", amountPosted) .addValue("previousBalance", previousBalance) } }
The output in a printStacktrace() (which often is written to a log) would look something like the following:
org.apache.commons.lang3.exception.ContextedException: java.lang.Exception: Error posting account transaction Exception Context: [accountNumber=null] [amountPosted=100.00] [previousBalance=-2.17] --------------------------------- at org.apache.commons.lang3.exception.ContextedExceptionTest.testAddValue(ContextedExceptionTest.java:88) ..... (rest of trace)
@see ContextedRuntimeException
@author Apache Software Foundation
@author D. Ashmore
@since 3.0