package cn.cslg.report.common;

import cn.cslg.report.common.core.exception.PermissionException;
import cn.cslg.report.common.utils.Response;
import cn.cslg.report.common.utils.ResponseEnum;
import cn.cslg.report.exception.XiaoShiException;
import cn.dev33.satoken.exception.NotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理类
 *
 * @Author chenyu
 * @Date 2023/7/3
 */
@Slf4j
@RestControllerAdvice // 可指定包前缀，比如：(basePackages = "com.pj.admin")
public class GlobalException {

    // 全局异常拦截（拦截项目中的所有异常）
    @ExceptionHandler
    public String handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 打印堆栈，以供调试
        e.printStackTrace();
        if (e instanceof NotLoginException) {
            return Response.error(ResponseEnum.UNAUTHORIZED);
        } else if (e instanceof PermissionException) {
            return Response.error(ResponseEnum.NOT_PERMISSION);
        } else {
            return Response.error(ResponseEnum.SYSTEM_ERROR);
        }
    }

    @ExceptionHandler
    public Response handleXiaoShiException(XiaoShiException e) {
        log.info("全局异常处理机制捕获到XiaoShiException，异常信息提示：{}", e.getMessage());
        return Response.fail(e.getMessage());
    }

}
