package top.imwork.commons.core.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.imwork.commons.core.pojo.ResponseMsg;

import java.io.Serial;

/**
 * Copyright (C), 2015-2021
 * FileName: BusinessException
 * Author(作者姓名):   jiangxiaowei
 * CreateDate(创建时间):     2021/8/2 14:58
 * UpdateDate(修改时间):     2021/8/2 14:58
 * Description(功能描述):    业务异常类
 * Since(版本号)  1.0.0
 * History:
 */
public class BusinessException extends RuntimeException {

    @Serial
    private static final long serialVersionUID = -1465322317086082432L;

    static final Logger logger = LoggerFactory.getLogger(BusinessException.class);

    public BusinessException(int code, String msg) throws JsonProcessingException {
        super(new ObjectMapper().writeValueAsString(ResponseMsg.buildResponse(code, msg)));
    }

    public BusinessException(int code, String msg, boolean isLog) throws JsonProcessingException {
        super(new ObjectMapper().writeValueAsString(ResponseMsg.buildResponse(code, msg)));
        if (isLog) {
            logger.error(new ObjectMapper().writeValueAsString(ResponseMsg.buildResponse(code, msg)));
        }
    }

    public BusinessException(Throwable e) {
        super(e);
    }

    public BusinessException(Throwable e, boolean isLog) {
        super(e);
        if (isLog) {
            logger.error(e.getMessage());
        }
    }

    public BusinessException(String message) {
        super(message);
    }

    public BusinessException(String message, boolean isLog) {
        super(message);
        if (isLog) {
            logger.error(message);
        }
    }

    public BusinessException(String message, Throwable e) {
        super(message, e);
    }

    public BusinessException(String message, Throwable e, boolean isLog) {
        super(message, e);
        if (isLog) {
            logger.error(message, e);
        }
    }
}
