shiro自定義異常沒法被捕獲老是拋出AuthenticationException解決方案

  這個問題我也是出的莫名其妙,剛開始好好的,而後配置多realm以後出的。apache

  如今直入主題ide

  在繼承了 org.apache.shiro.authc.pam.ModularRealmAuthenticator的類中重寫doMultiRealmAuthentication方法spa

  如下是重寫的代碼,判斷是否存在異常。若是存在異常,則拋出。debug

public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {

private static final Logger log = LoggerFactory.getLogger(ModularRealmAuthenticator.class);

@Override
protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) throws AuthenticationException {
AuthenticationStrategy strategy = getAuthenticationStrategy();

AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);

if (log.isTraceEnabled()) {
log.trace("Iterating through {} realms for PAM authentication", realms.size());
}
AuthenticationException authenticationException = null;
for (Realm realm : realms) {

aggregate = strategy.beforeAttempt(realm, token, aggregate);

if (realm.supports(token)) {

log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);

AuthenticationInfo info = null;
try {
info = realm.getAuthenticationInfo(token);
} catch (AuthenticationException e) {
authenticationException = e;
if (log.isDebugEnabled()) {
String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
log.debug(msg, e);
}
}

aggregate = strategy.afterAttempt(realm, token, info, aggregate, authenticationException);

} else {
log.debug("Realm [{}] does not support token {}. Skipping realm.", realm, token);
}
}
if(authenticationException != null){
throw authenticationException;
}
aggregate = strategy.afterAllAttempts(token, aggregate);

return aggregate;
}
}

 

  關鍵點在於code

    if(authenticationException != null){
            throw authenticationException;
        }
 
有可能出現的問題。。。
可能會出現第二個realm會出現第一個realm的拋出的異常。樓主直接在subject.login(token);try處理了。。
若是想在第二個realm裏throw new ,別拋出RuntimeException這個就行。。。
try {
    subject.login(token);
}catch (LoginPhoneException e){
    Map map = new HashMap();
    map.put("code", CodeAndMsgEnum.INFO.getCode());
    return map;
}catch (RuntimeException e){
    System.out.println("出現了這個異常。。。可是無論他,由於我也不知道怎麼處理");
}
瞎搞一通,總之解決了問題,可是我的以爲有點不理想,算了,但願能夠找到更好的解決方法。
相關文章
相關標籤/搜索