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