springboot+shiro做统一的异常处理

4 篇文章 0 订阅
4 篇文章 0 订阅

1.shiro的常见异常

1.1 AuthencationException:
    AuthenticationException 异常是Shiro在登录认证过程中,认证失败需要抛出的异常。 AuthenticationException包含以下子类:
  • CredentitalsException 凭证异常

        IncorrectCredentialsException 不正确的凭证
        ExpiredCredentialsException 凭证过期
    
  • AccountException 账号异常

        ConcurrentAccessException 并发访问异常(多个用户同时登录时抛出)
        UnknownAccountException 未知的账号
        ExcessiveAttemptsException 认证次数超过限制
        DisabledAccountException 禁用的账号
            LockedAccountException 账号被锁定
    
  • UnsupportedTokenException 使用了不支持的Token

1.2AuthorizationException:

子类:

  • UnauthorizedException:抛出以指示请求的操作或对请求的资源的访问是不允许的。

  • UnanthenticatedException:当尚未完成成功认证时,尝试执行授权操作时引发异常。

2.异常处理方法

2.1在shiro配置文件中配置
2.1.1自己创建GlobalExceptionResolver
public class GlobalExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mv;
        System.out.println(ex instanceof UnauthenticatedException);
        //进行异常判断。如果捕获异常请求跳转。
        if (ex instanceof UnauthorizedException) {
        	mv = new ModelAndView("/error/error");
            ex.printStackTrace();
            mv.addObject("msg", "你的级别还不够高,加油吧!少年。");  
            return mv;
        }
        else if(ex instanceof UnauthenticatedException){
            mv = new ModelAndView("/error/error");
            ex.printStackTrace();
            mv.addObject("msg", "没有此权限!");          
            return mv;
        }      
        else {
            mv = new ModelAndView("/error/error");
            ex.printStackTrace();
            mv.addObject("msg", "我勒个去,页面被外星人挟持了!");          
            return mv;

        }

    }
}
2.1.2在ShiroConfiguration中配置
@Bean(name = "exceptionHandler")
  public HandlerExceptionResolver handlerExceptionResolver(){
      return new GlobalExceptionResolver();
}
2.2 使用@ExceptionHandler配置

创建异常处理类:这是基于springmvc的

@ControllerAdvice
public class AllException{
	  @ExceptionHandler
       public String exceptiona(Exception ex) {		 
    	   if(ex instanceof UnauthenticatedException) {
    		   return "redirect:/login";    		 
    	     }
    	   else if(ex instanceof UnauthorizedException) {
    		   return "error/error";
 		     }
    	   else if(ex instanceof Exception){
    		   
    	     }
    	   return null;
       }
}

注意:此类必须要被继承才能生效。如loginController类 想要捕获类中的异常。
如:
public class AccoutController extends AllException

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值