
package uk.co.wingpath.util;

/**
* This class provides some utility methods for use with exceptions.
*/
public class Exceptions
{
    private Exceptions ()
    {
    }

    /**
    * Gets the unqualified class name of an exception.
    * @param ex the exception
    * @return the unqualified class name of the exception.
    */
    public static String getName (Throwable ex)
    {
        String name = ex.getClass ().getName ();
        int i = name.lastIndexOf ('.');
        if (i >= 0)
            name = name.substring (i + 1);
        return name;
    }

    /**
    * Gets the message from an exception.
    * <p>If no message was stored in the exception, the unqualified class
    * name of the exception is used instead.
    * <p>If the exception has a cause and the cause has a stored message,
    * the cause message is appended to the returned message.
    * @param ex the exception.
    * @return message extracted from the exception.
    */
    public static String getMessage (Throwable ex)
    {
        String msg = ex.getMessage ();
        if (msg == null)
            msg = getName (ex);
        Throwable c = ex.getCause ();
        if (c != null && c.getMessage () != null)
            msg = msg + ": " + c.getMessage ();
        return msg;
    }

    /**
    * Gets the help ID, if any, from an exception.
    * @param ex the exception.
    * @return the help ID, or null is the exception doesn't have one.
    */
    public static String getHelpId (Throwable ex)
    {
        if (ex instanceof Helpful)
            return ((Helpful) ex).getHelpId ();
        return null;
    }
}


