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.dev33.satoken.exception.NotLoginException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

/**
 * 全局异常处理
 */
@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);
        }
    }
}
