/*
 * Copyright (C) 2020 The zfoo Authors
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

package com.zfoo.protocol.exception;

import com.zfoo.protocol.util.FileUtils;
import com.zfoo.protocol.util.StringUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;

public abstract class ExceptionUtils {

    /**
     * 获取异常全部信息，格式是：
     * <p>
     * 类名称: 异常信息
     * 异常堆栈
     * </p>
     *
     * @param throwable the throwable to get a message for, null returns empty string
     * @return 异常的信息
     */
    public static String getMessage(final Throwable throwable) {
        if (throwable == null) {
            return StringUtils.EMPTY;
        }
        final String className = throwable.getClass().getName();
        return className + ": " + throwable.getMessage() + FileUtils.LS
                + getStackTrace(throwable);
    }


    /**
     * <p>Gets the stack trace from a Throwable as a String.</p>
     * <p>The result of this method vary by JDK version as this method uses {@link Throwable#printStackTrace(java.io.PrintWriter)}.
     *
     * @param throwable the <code>Throwable</code> to be examined
     * @return the stack trace as generated by the exception's
     */
    public static String getStackTrace(final Throwable throwable) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        throwable.printStackTrace(pw);
        return sw.getBuffer().toString();
    }

    public static String getCurrentStackTrace() {
        var builder = new StringBuilder();
        var stackTraces = Thread.currentThread().getStackTrace();
        Arrays.stream(stackTraces).forEach(it -> builder.append(it.toString()).append(FileUtils.LS));
        return builder.toString();
    }

}
