如何在android中创建自己的VolleyError对象

时间:2018-01-27 11:17:52

标签: android android-volley

我主要使用Volley在我的Android应用中进行网络调用。 Volley总是有两个回调:

1)onSuccess(字符串响应)

2)onError(VolleyError错误)

现在我对这个VolleyError对象更感兴趣。此object可以是NetworkErrorAuthFailureErrorTimeoutError等的实例。

我想创建自己的VolleyError AuthFailureError类型的对象。这样我就可以将该对象传递给回调方法。

这是我的方法:

if ((currentTime - refreshTime) < (expiresInFromPrefs - 5)) {
                //token is live
                tokenCallback.success(accessTokenFromPrefs);
            }else{
                //token expired
                Log.e(TAG,"token expired");
                tokenCallback.failure(VolleyError myObject);
            }

这就是VolleyError类的样子:

public class VolleyError extends Exception {
    public final NetworkResponse networkResponse;
    private long networkTimeMs;

    public VolleyError() {
        networkResponse = null;
    }

    public VolleyError(NetworkResponse response) {
        networkResponse = response;
    }

    public VolleyError(String exceptionMessage) {
       super(exceptionMessage);
       networkResponse = null;
    }

    public VolleyError(String exceptionMessage, Throwable reason) {
        super(exceptionMessage, reason);
        networkResponse = null;
    }

    public VolleyError(Throwable cause) {
        super(cause);
        networkResponse = null;
    }

    /* package */ void setNetworkTimeMs(long networkTimeMs) {
       this.networkTimeMs = networkTimeMs;
    }

    public long getNetworkTimeMs() {
       return networkTimeMs;
    }
}

这就是AuthFailureError的样子:

public class AuthFailureError extends VolleyError {
    /** An intent that can be used to resolve this exception. (Brings up the password dialog.) */
    private Intent mResolutionIntent;

    public AuthFailureError() { }

    public AuthFailureError(Intent intent) {
        mResolutionIntent = intent;
    }

    public AuthFailureError(NetworkResponse response) {
        super(response);
    }

    public AuthFailureError(String message) {
        super(message);
    }

    public AuthFailureError(String message, Exception reason) {
        super(message, reason);
    }

    public Intent getResolutionIntent() {
        return mResolutionIntent;
    }

    @Override
    public String getMessage() {
        if (mResolutionIntent != null) {
            return "User needs to (re)enter credentials.";
        }
        return super.getMessage();
    }
}

2 个答案:

答案 0 :(得分:0)

  

我想创建自己的类型为AuthFailureError的VolleyError对象

然后,您需要扩展AuthFailureError而不是Exception

public class VolleyError extends AuthFailureError

因为,Exception类的扩展会使VolleyError的类类型Exception不是AuthFailureError类。

答案 1 :(得分:0)

我假设您实施了custom Volley request。您不需要扩展VolleyError类,只需使用其中一个构造函数,例如

public VolleyError(Throwable cause)

从您的自定义请求中传递自定义错误(必须是Throwable)。