package com.yanzuoguang.util.exception;

import com.yanzuoguang.util.contants.ResultConstants;
import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log;
import com.yanzuoguang.util.vo.ResponseResult;

/**
 * 异常处理帮助类
 *
 * @author 颜佐光
 */
public class ExceptionHelper {
    /**
     * 不跑出异常,记录日常日志
     *
     * @param cls 错误类型
     * @param ex  错误
     */
    public static void handleException(Class<?> cls, Throwable ex) {
        handleException(cls, ex, null);
    }

    /**
     * 不抛出异常,记录日常日志
     *
     * @param cls  错误类型
     * @param ex   错误
     * @param from 错误资源
     */
    public static void handleException(Class<?> cls, Throwable ex, Object from) {
        Log.error(cls, ex, StringHelper.EMPTY, from);
    }

    /**
     * 异常信息输出
     *
     * @param local  字符串
     * @param start  开始位置
     * @param end    结束位置
     * @param length 总长度
     * @param str    结果
     */
    public static void subStringException(String local, int start, int end, int length, String str) {
        String exception = local + "/n" + "开始:" + start + " 结束:" + end + "总长:" + length + "/n" + str;
        throw new CodeException(exception);
    }


    /**
     * 根据异常获取返回数据
     *
     * @param e 异常信息
     * @return 返回的数据
     */
    public static ResponseResult<?> getError(Exception e) {
        return getError(e, false);
    }

    /**
     * 根据异常获取返回数据
     *
     * @param e 异常信息
     * @return 返回的数据
     */
    public static ResponseResult<?> getError(Exception e, boolean isFull) {
        boolean isFullTo = e instanceof CodeTargetException || isFull;
        boolean codeError = e instanceof CodeException;

        ResponseResult<?> result;
        if (e instanceof RuntimeCodeException) {
            RuntimeCodeException code = (RuntimeCodeException) e;
            result = getError(code.getCode(), code.getMessage(), code.getTarget(), isFullTo);
        } else {
            String msg = e.getMessage();
            if (StringHelper.isEmpty(msg)) {
                msg = e.getClass().getName();
            }
            result = getError(ResultConstants.UNKNOW_ERROR, msg, e, isFullTo);
        }
        result.setCodeError(codeError);
        return result;
    }

    private static ResponseResult<?> getError(String code, String msg, Object target, boolean isFull) {
        if (isFull) {
            return ResponseResult.error(code, msg, target);
        } else {
            return ResponseResult.error(code, msg);
        }
    }
}