package cn.hanghui.outapi.platform.common.exception;

import cn.hanghui.outapi.platform.common.entity.rest.RespCodeEnum;
import cn.hutool.core.util.ObjectUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
public class CommonException extends RuntimeException {

    private String errCode;

    private String errMsg;

    private Exception sysException;

    public CommonException(Exception sysException) {
        this.errCode = RespCodeEnum.SYS_ERROR.code;
        this.errMsg = RespCodeEnum.SYS_ERROR.msg;
        this.sysException = sysException;
    }

    public CommonException(String msg, Exception sysException) {
        if (sysException instanceof CommonException) {
            CommonException e = (CommonException) sysException;
            this.errMsg = e.errMsg;
            this.errCode = e.errCode;
        } else {
            this.errCode = RespCodeEnum.SYS_ERROR.code;
            this.errMsg = msg;
        }
        this.sysException = sysException;
    }

    public CommonException() {
        this.errCode = RespCodeEnum.SYS_ERROR.code;
        this.errMsg = RespCodeEnum.SYS_ERROR.msg;
    }

    public CommonException(String errMsg) {
        this.errCode = RespCodeEnum.BIZ_ERROR.code;
        this.errMsg = errMsg;
    }

    public CommonException(RespCodeEnum respCodeEnum) {
        this.errCode = respCodeEnum.code;
        this.errMsg = respCodeEnum.msg;
    }

    @Override
    public String getMessage() {
        return errCode + ":" + errMsg;
    }

    @Override
    public synchronized Throwable fillInStackTrace() {
        if (ObjectUtil.isNotEmpty(sysException) && !(sysException instanceof CommonException)) {
            return sysException;
        }
        return this;
    }
}
