    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.lang3.exception;
    018
    019import java.util.List;
    020import java.util.Set;
    021
    022import org.apache.commons.lang3.tuple.Pair;
    023
    024/**
    025 * <p>
    026 * An exception that provides an easy and safe way to add contextual information.
    027 * </p><p>
    028 * An exception trace itself is often insufficient to provide rapid diagnosis of the issue.
    029 * Frequently what is needed is a select few pieces of local contextual data.
    030 * Providing this data is tricky however, due to concerns over formatting and nulls.
    031 * </p><p>
    032 * The contexted exception approach allows the exception to be created together with a
    033 * list of context label-value pairs. This additional information is automatically included in
    034 * the message and printed stack trace.
    035 * </p><p>
    036 * An unchecked version of this exception is provided by ContextedRuntimeException.
    037 * </p>
    038 * <p>
    039 * To use this class write code as follows:
    040 * </p>
    041 * <pre>
    042 *   try {
    043 *     ...
    044 *   } catch (Exception e) {
    045 *     throw new ContextedException("Error posting account transaction", e)
    046 *          .addContextValue("Account Number", accountNumber)
    047 *          .addContextValue("Amount Posted", amountPosted)
    048 *          .addContextValue("Previous Balance", previousBalance);
    049 *   }
    050 * }
    051 * </pre>
    052 * <p>
    053 * or improve diagnose data at a higher level:
    054 * </p>
    055 * <pre>
    056 *   try {
    057 *     ...
    058 *   } catch (ContextedException e) {
    059 *     throw e.setContextValue("Transaction Id", transactionId);
    060 *   } catch (Exception e) {
    061 *     if (e instanceof ExceptionContext) {
    062 *       e.setContextValue("Transaction Id", transactionId);
    063 *     }
    064 *     throw e;
    065 *   }
    066 * }
    067 * </pre>
    068 * <p>
    069 * The output in a printStacktrace() (which often is written to a log) would look something like the following:
    070 * </p>
    071 * <pre>
    072 * org.apache.commons.lang3.exception.ContextedException: java.lang.Exception: Error posting account transaction
    073 *  Exception Context:
    074 *  [1:Account Number=null]
    075 *  [2:Amount Posted=100.00]
    076 *  [3:Previous Balance=-2.17]
    077 *  [4:Transaction Id=94ef1d15-d443-46c4-822b-637f26244899]
    078 *
    079 *  ---------------------------------
    080 *  at org.apache.commons.lang3.exception.ContextedExceptionTest.testAddValue(ContextedExceptionTest.java:88)
    081 *  ..... (rest of trace)
    082 * </pre>
    083 *
    084 * @see ContextedRuntimeException
    085 * @since 3.0
    086 */
    087public class ContextedException extends Exception implements ExceptionContext {
    088
    089    /** The serialization version. */
    090    private static final long serialVersionUID = 20110706L;
    091    /** The context where the data is stored. */
    092    private final ExceptionContext exceptionContext;
    093
    094    /**
    095     * Instantiates ContextedException without message or cause.
    096     * <p>
    097     * The context information is stored using a default implementation.
    098     */
    099    public ContextedException() {
    100        exceptionContext = new DefaultExceptionContext();
    101    }
    102
    103    /**
    104     * Instantiates ContextedException with message, but without cause.
    105     * <p>
    106     * The context information is stored using a default implementation.
    107     *
    108     * @param message  the exception message, may be null
    109     */
    110    public ContextedException(final String message) {
    111        super(message);
    112        exceptionContext = new DefaultExceptionContext();
    113    }
    114
    115    /**
    116     * Instantiates ContextedException with cause, but without message.
    117     * <p>
    118     * The context information is stored using a default implementation.
    119     *
    120     * @param cause  the underlying cause of the exception, may be null
    121     */
    122    public ContextedException(final Throwable cause) {
    123        super(cause);
    124        exceptionContext = new DefaultExceptionContext();
    125    }
    126
    127    /**
    128     * Instantiates ContextedException with cause and message.
    129     * <p>
    130     * The context information is stored using a default implementation.
    131     *
    132     * @param message  the exception message, may be null
    133     * @param cause  the underlying cause of the exception, may be null
    134     */
    135    public ContextedException(final String message, final Throwable cause) {
    136        super(message, cause);
    137        exceptionContext = new DefaultExceptionContext();
    138    }
    139
    140    /**
    141     * Instantiates ContextedException with cause, message, and ExceptionContext.
    142     *
    143     * @param message  the exception message, may be null
    144     * @param cause  the underlying cause of the exception, may be null
    145     * @param context  the context used to store the additional information, null uses default implementation
    146     */
    147    public ContextedException(final String message, final Throwable cause, ExceptionContext context) {
    148        super(message, cause);
    149        if (context == null) {
    150            context = new DefaultExceptionContext();
    151        }
    152        exceptionContext = context;
    153    }
    154
    155    //-----------------------------------------------------------------------
    156    /**
    157     * Adds information helpful to a developer in diagnosing and correcting the problem.
    158     * For the information to be meaningful, the value passed should have a reasonable
    159     * toString() implementation.
    160     * Different values can be added with the same label multiple times.
    161     * <p>
    162     * Note: This exception is only serializable if the object added is serializable.
    163     * </p>
    164     *
    165     * @param label  a textual label associated with information, {@code null} not recommended
    166     * @param value  information needed to understand exception, may be {@code null}
    167     * @return {@code this}, for method chaining, not {@code null}
    168     */
    169    @Override
    170    public ContextedException addContextValue(final String label, final Object value) {
    171        exceptionContext.addContextValue(label, value);
    172        return this;
    173    }
    174
    175    /**
    176     * Sets information helpful to a developer in diagnosing and correcting the problem.
    177     * For the information to be meaningful, the value passed should have a reasonable
    178     * toString() implementation.
    179     * Any existing values with the same labels are removed before the new one is added.
    180     * <p>
    181     * Note: This exception is only serializable if the object added as value is serializable.
    182     * </p>
    183     *
    184     * @param label  a textual label associated with information, {@code null} not recommended
    185     * @param value  information needed to understand exception, may be {@code null}
    186     * @return {@code this}, for method chaining, not {@code null}
    187     */
    188    @Override
    189    public ContextedException setContextValue(final String label, final Object value) {
    190        exceptionContext.setContextValue(label, value);
    191        return this;
    192    }
    193
    194    /**
    195     * {@inheritDoc}
    196     */
    197    @Override
    198    public List<Object> getContextValues(final String label) {
    199        return this.exceptionContext.getContextValues(label);
    200    }
    201
    202    /**
    203     * {@inheritDoc}
    204     */
    205    @Override
    206    public Object getFirstContextValue(final String label) {
    207        return this.exceptionContext.getFirstContextValue(label);
    208    }
    209
    210    /**
    211     * {@inheritDoc}
    212     */
    213    @Override
    214    public List<Pair<String, Object>> getContextEntries() {
    215        return this.exceptionContext.getContextEntries();
    216    }
    217
    218    /**
    219     * {@inheritDoc}
    220     */
    221    @Override
    222    public Set<String> getContextLabels() {
    223        return exceptionContext.getContextLabels();
    224    }
    225
    226    /**
    227     * Provides the message explaining the exception, including the contextual data.
    228     *
    229     * @see java.lang.Throwable#getMessage()
    230     * @return the message, never null
    231     */
    232    @Override
    233    public String getMessage() {
    234        return getFormattedExceptionMessage(super.getMessage());
    235    }
    236
    237    /**
    238     * Provides the message explaining the exception without the contextual data.
    239     *
    240     * @see java.lang.Throwable#getMessage()
    241     * @return the message
    242     * @since 3.0.1
    243     */
    244    public String getRawMessage() {
    245        return super.getMessage();
    246    }
    247
    248    /**
    249     * {@inheritDoc}
    250     */
    251    @Override
    252    public String getFormattedExceptionMessage(final String baseMessage) {
    253        return exceptionContext.getFormattedExceptionMessage(baseMessage);
    254    }
    255}