新着!Shiroカスタム例外をキャッチできない常にAuthenticationExceptionソリューションをスローする

1.理由

AuthorizingRealmdoGetAuthenticationInfoで例外をスローします

場合:

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

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

結果:

{
    
    
  "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"
}

2つ目は、グローバルな傍受の失敗を作成するときです。

たとえば、グローバルキャプチャの@RestControllerAdvice

    /**
     * 捕捉业务相关异常
     */
    @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);
    }

注:グローバルキャプチャは失敗しました

  • 結論:
    ソースコードはそれ自体のコードに問題がないため、外部はdoGetAuthenticationInfoメソッドによってスローされた例外をキャッチできません。
    ソースコードを書き直す機能がない場合、さまざまな例外をキャッチしてフロントエンドにさまざまなプロンプトを表示するにはどうすればよいですか?

三、最終計画

1.認証の失敗を返します
2.応答ヘッダーを再定義します

  • ステップ1:認証の失敗を返す
        if(o == null){
    
    
            //token为null,返回错误信息,并且拒绝访问
            responseError(servletResponse, HttpCodeEnum.UNAUTHORIZED.getCode(),"token失效了!");
            return false;
        }
  • ステップ2:応答ヘッダーを再定義する
        JsonResult jsonResult = new JsonResult(code,errorMsg,null);
        OutputStream os = httpServletResponse.getOutputStream();
        os.write(new ObjectMapper().writeValueAsString(jsonResult).getBytes("UTF-8"));
        os.flush();
        os.close();

おすすめ

転載: blog.csdn.net/qq_34168515/article/details/112407373