package com.dragonsoft.tryapp.common.exceptions;

/**
 * Used to handle certain exceptions.
 */
public final class ExceptionHandler {

    private static final String START = "[START ERROR FOUND:";

    private static final String CATCHER = "\nThe Exception was caught by: ";

    private static final String GENERAL = "\nThe Error was an: ";

    private static final String MESSAGE = "\nThe Error had a message: ";

    private static final String SOURCE = "\nThe Source of the error was: ";

    private static final String RECURSE = "\nThe Source's Error was : ";

    private static final String END = "\nEND OF ERROR]";

    public static void logException(Throwable thr, Object catcher) {
        System.out.println(createExceptionLog(thr, catcher));
    }

    private static String createExceptionLog(Throwable thrower, Object catcher) {
        StringBuffer buffer = new StringBuffer(START);
        if (catcher != null) {
            buffer.append(CATCHER).append(catcher.getClass().toString());
        }
        buffer.append(GENERAL).append(thrower.getClass().toString());
        if (thrower.getMessage() != null)
            buffer.append(MESSAGE).append(thrower.getMessage());
        if (thrower.getCause() != null) {
            buffer.append(SOURCE).append(thrower.getCause());
            buffer.append(RECURSE).append(
                    createExceptionLog(thrower.getCause(), null));
        }
        buffer.append(END);
        return buffer.toString();
    }

    public static void main(String args[]) {

        try {
            try {
                throw new NullPointerException();
            } catch (NullPointerException e) {
                throw new TryException("ExceptionHandler: Test", e);
            }
        } catch (TryException e) {
            ExceptionHandler.logException(e, new Object());
        }
    }

} // ExceptionHandler