package com.sysu.admin.support.shiro;

import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @title ShiroRestExceptionAdvice
 * @description
 * @author XIE
 * @date 2020年4月24日下午10:09:38
 */
@Slf4j
@RestControllerAdvice
public class ShiroRestExceptionAdvice {

    /**
     * 认知授权错误
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler({UnauthorizedException.class, UnauthenticatedException.class})
    public BaseResult shiroException(HttpServletRequest request, Exception e) {
        log.error("shiroException ......", e);
        String msg = "";
        if (e instanceof UnauthenticatedException) {
            msg = "未认证：" + e.getMessage();
        } else if (e instanceof UnauthorizedException) {
            msg = "未授权：" + e.getMessage();
        } else {
            msg = "未知";
        }
        return R.error(msg);
    }
}
