package cn.cslg.pas.common;

import cn.cslg.pas.common.core.exception.PermissionException;
import cn.cslg.pas.common.utils.Response;
import cn.cslg.pas.common.utils.ResponseEnum;
import cn.cslg.pas.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;
import java.io.IOException;

/**
 * 全局异常处理
 */
@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) {
            NotLoginException notLoginException = (NotLoginException) e;
            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());
    }

    @ExceptionHandler
    public Response handleIOException(IOException e) {
        log.info("全局异常处理机制捕获到IOException，异常信息打桩输出为：");
        e.printStackTrace();
        return Response.fail();
    }

    @ExceptionHandler
    public Response handleThrowable(Throwable e) {
        log.info("全局异常处理机制捕获到Throwable，异常信息打桩输出为：");
        e.printStackTrace();
        return Response.fail();
    }

}
