You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何自定义AuthFailureError类型的VolleyError对象?

解决方案:创建自定义AuthFailureError用于Volley回调

Got it, let's sort this out for you. You want to generate a custom AuthFailureError instance to pass to your tokenCallback.failure() method when your access token expires—here's exactly how to do it, with options based on your needs:

1. 基础用法(最简单的实现)

If you just need to signal an auth failure without extra details, use the no-argument constructor of AuthFailureError:

}else{ 
    //token已过期
    Log.e(TAG,"token expired"); 
    // 直接创建AuthFailureError实例
    tokenCallback.failure(new AuthFailureError()); 
}

This will use the default message defined in AuthFailureError.getMessage(): "User needs to (re)enter credentials."

2. 自定义错误消息

If you want to add a specific message about the token expiration, use the constructor that accepts a string:

}else{ 
    //token已过期
    Log.e(TAG,"token expired"); 
    // 创建带自定义消息的AuthFailureError
    AuthFailureError expiredTokenError = new AuthFailureError("Access token has expired. Please re-authenticate.");
    tokenCallback.failure(expiredTokenError); 
}

When you call getMessage() on this error later, it will return your custom string instead of the default.

3. 附带跳转验证界面的Intent

If you want to trigger a login/credential re-entry flow directly from the error, pass an Intent to the constructor:

}else{ 
    //token已过期
    Log.e(TAG,"token expired"); 
    // 创建跳转到登录页面的Intent
    Intent loginIntent = new Intent(getContext(), LoginActivity.class);
    // 用Intent初始化AuthFailureError
    AuthFailureError authErrorWithIntent = new AuthFailureError(loginIntent);
    tokenCallback.failure(authErrorWithIntent); 
}

Later, in your callback's failure() method, you can retrieve this intent with error.getResolutionIntent() and start the login activity to let the user re-authenticate.

为什么这可行?

Since AuthFailureError is a subclass of VolleyError, it's fully compatible with the failure(VolleyError error) callback method. The Volley callback will accept it just like any other VolleyError instance, and you can check the error type later with instanceof if needed:

@Override
public void failure(VolleyError error) {
    if (error instanceof AuthFailureError) {
        // 处理认证失败逻辑,比如跳转登录
        AuthFailureError authError = (AuthFailureError) error;
        Intent loginIntent = authError.getResolutionIntent();
        if (loginIntent != null) {
            startActivity(loginIntent);
        }
    }
}

内容的提问来源于stack exchange,提问作者sagar suri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:38:31