package com.svbio.workflow.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * This class consists exclusively of static utility methods for {@link Throwable} instances.
 */
public final class Throwables {
    private Throwables() {
        throw new AssertionError(String.format("No %s instances for you!", getClass().getName()));
    }

    /**
     * Returns a string containing the stack trace of the given {@link Throwable}.
     *
     * <p>The returned string is equal to the output generated by {@link Throwable#printStackTrace}.
     *
     * @param throwable the {@link Throwable} instance
     * @return string containing the stack trace of the given {@link Throwable}
     */
    public static String executionTraceToString(Throwable throwable) {
        try (
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter)
        ) {
            throwable.printStackTrace(printWriter);
            printWriter.close();
            return stringWriter.toString();
        } catch (IOException exception) {
            throw new IllegalStateException("Unexpected IOException from StringWriter", exception);
        }
    }
}
