new! Shiro custom exception cannot be caught always throw AuthenticationException solution

1. Reasons

Throw an exception in AuthorizingRealm doGetAuthenticationInfo

Case:

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken){
    
    
        String token = (String) authenticationToken.getCredentials();

        if(true){
    
    
            throw new BusinessException("报错");
        }

result:

{
    
    
  "timestamp": "2021-01-09T13:11:56.348+0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "Authentication failed for token submission [com.cancan.daxiangerp.utils.JWTToken@79e56cc5].  Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).",
  "path": "/user/dx-user/query"
}

Two, when we create a global interception failure

For example @RestControllerAdvice for global capture

    /**
     * 捕捉业务相关异常
     */
    @ExceptionHandler(BusinessException.class)
    public JsonResult handle10000(BusinessException e) {
    
    
        log.error("异常{}的信息为:{}",HttpCodeEnum.BUSINESS_ERROR.getCode(),e.getMessage());
        return new JsonResult(HttpCodeEnum.BUSINESS_ERROR.getCode(), e.getMessage(), null);
    }

Note: Global capture failed

  • Conclusion: The
    external cannot catch the exception thrown by the doGetAuthenticationInfo method, because the source code is not a problem with its own code.
    If you don't have the ability to rewrite the source code, what should you do if you want to catch various exceptions and display various prompts on the front end?

Three, the final plan

1. Return authentication failure
2. Redefine the response header

  • Step 1: Return authentication failure
        if(o == null){
    
    
            //token为null,返回错误信息,并且拒绝访问
            responseError(servletResponse, HttpCodeEnum.UNAUTHORIZED.getCode(),"token失效了!");
            return false;
        }
  • Step 2: Redefine the response header
        JsonResult jsonResult = new JsonResult(code,errorMsg,null);
        OutputStream os = httpServletResponse.getOutputStream();
        os.write(new ObjectMapper().writeValueAsString(jsonResult).getBytes("UTF-8"));
        os.flush();
        os.close();

Guess you like

Origin blog.csdn.net/qq_34168515/article/details/112407373