我主要使用Volley
在我的Android应用中进行网络调用。 Volley
总是有两个回调:
1)onSuccess(字符串响应)
2)onError(VolleyError错误)
现在我对这个VolleyError对象更感兴趣。此object
可以是NetworkError
,AuthFailureError
,TimeoutError
等的实例。
我想创建自己的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();
}
}
答案 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
)。