gpt4 book ai didi

android - Volley 错误处理广义化

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:28 25 4
gpt4 key购买 nike

在我的应用程序中,我一直在思考从服务器实现 5xx 响应的最佳方式。
第一种方法是编写我自己版本的Request.deliverError 方法,如附件所示:

@Override
public void deliverError(VolleyError error) {
if(error.networkResponse == null){
super.deliverError(error);
return;
}else {
switch(error.networkResponse.statusCode){
case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
AppInfo.reportDevInfo(GlideApplication.applicationContext, "got a 505 response for request" +this.toString(), null);
break;
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
case HttpStatus.SC_BAD_GATEWAY:
case HttpStatus.SC_SERVICE_UNAVAILABLE:
case HttpStatus.SC_GATEWAY_TIMEOUT:
int retryCount = RETRY_COUNT - getRetryPolicy().getCurrentRetryCount();
if(retryCount < 0) {
super.deliverError(error);
return;
}
String backoff = error.networkResponse.getHeaders.get("Retry-After");
if(TextUtils.isEmpty(backoof) == false) {
attemptRetryWithNewBackoff(backoff);
return;
}
break;
}
super.deliverError(error)
}
}
}

但这只会导致应用程序出现 ANR。

通过进一步研究,我发现了 this blog post这显示了一种处理不同响应代码的方法,唯一的问题是我不确定如何将其推广到我的整个应用程序并使用适当的“Retry-After”标题实现对 5xx 响应代码的处理。

拥有一个实现 ErrorListener 的类并在构造函数中获取一个不同的类作为参数似乎非常昂贵且效率低下:

public class MyErrorListener implements ErrorListener {
ErrorListener mListener;

public MyErrorListener(ErrorListener listener) {
this.mListener = listener;
}

@Override
public void onErrorResponse(VolleyError error) {
if(handleFiveHundredResponse(error) == false) {
this.mListener.onErrorResponse(error);
}
}

}

最佳答案

我知道答案有点晚了,但我相信它肯定会帮助新手寻找这个,这就是我所做的。

在 Kotlin 中:

请求

val request = object : JsonObjectRequest(Method.POST,
url,
reqObj,
{}, { error ->
Toast.makeText(this, getVolleyError(error), Toast.LENGTH_LONG).show()
}) {
}
RequestController.getInstance().addToRequestQueue(request)

getVolleyError(错误:VolleyError)

fun Activity.getVolleyError(error: VolleyError): String {
var errorMsg = ""
if (error is NoConnectionError) {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
var activeNetwork: NetworkInfo? = null
activeNetwork = cm.activeNetworkInfo
errorMsg = if (activeNetwork != null && activeNetwork.isConnectedOrConnecting) {
"Server is not connected to the internet. Please try again"
} else {
"Your device is not connected to internet.please try again with active internet connection"
}
} else if (error is NetworkError || error.cause is ConnectException) {
errorMsg = "Your device is not connected to internet.please try again with active internet connection"
} else if (error.cause is MalformedURLException) {
errorMsg = "That was a bad request please try again…"
} else if (error is ParseError || error.cause is IllegalStateException || error.cause is JSONException || error.cause is XmlPullParserException) {
errorMsg = "There was an error parsing data…"
} else if (error.cause is OutOfMemoryError) {
errorMsg = "Device out of memory"
} else if (error is AuthFailureError) {
errorMsg = "Failed to authenticate user at the server, please contact support"
} else if (error is ServerError || error.cause is ServerError) {
errorMsg = "Internal server error occurred please try again...."
} else if (error is TimeoutError || error.cause is SocketTimeoutException || error.cause is ConnectTimeoutException || error.cause is SocketException || (error.cause!!.message != null && error.cause!!.message!!.contains(
"Your connection has timed out, please try again"
))
) {
errorMsg = "Your connection has timed out, please try again"
} else {
errorMsg = "An unknown error occurred during the operation, please try again"
}
return errorMsg
}

我上面使用的方法是kotlin的一个扩展函数,只能从activity中调用,如果要从另一个scope中调用同样的方法,那就得修改了。必须有一个 Activity 实例来检查互联网连接


在 Java 中:

请求

JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST,"url",null,new Response.Listener<JSONObject>(){
@Override
public void onResponse(JSONObject response){

}
},new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
Toast.makeText(this, getVolleyError(error), Toast.LENGTH_LONG).show()
}
});
RequestController.getInstance().addToRequestQueue(request);

getVolleyError(VolleyError 错误)

public String getVolleyError(VolleyError error){
String errorMsg="";
if(error instanceof NoConnectionError){
ConnectivityManager cm=(ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork=null;
if(cm!=null){
activeNetwork=cm.getActiveNetworkInfo();

}
if(activeNetwork!=null&&activeNetwork.isConnectedOrConnecting()){
errorMsg="Server is not connected to internet.kindly try agian";
}else{
errorMsg="Your device is not connected to internet.please try again with active internet connection";
}
}else if(error instanceof NetworkError||error.getCause()instanceof ConnectException){
errorMsg="Your device is not connected to the internet.";
}else if(error.getCause()instanceof MalformedURLException){
errorMsg="That was a bad request please try again...";
}else if(error instanceof ParseError||error.getCause()instanceof IllegalStateException
||error.getCause()instanceof JSONException
||error.getCause()instanceof XmlPullParserException){
errorMsg="There was an error parsing data...";
}else if(error.getCause()instanceof OutOfMemoryError){
errorMsg="Device out of memory";
}else if(error instanceof AuthFailureError){
errorMsg="Failed to authenticate user at the server, please contact support";
}else if(error instanceof ServerError||error.getCause()instanceof ServerError){
errorMsg="Internal server error occurred please try again....";
}else if(error instanceof TimeoutError||error.getCause()instanceof SocketTimeoutException
||error.getCause()instanceof ConnectTimeoutException
||error.getCause()instanceof SocketException
||(error.getCause().getMessage()!=null
&&error.getCause().getMessage().contains("Connection timed out"))){
errorMsg="Your connection has timed out, please try again";
}else{
errorMsg="Sorry, some thing weird occurred";
}
return errorMsg;
}

上面的方法应该需要一个activity的实例来检查连通性,你可以按照你的逻辑提供它

关于android - Volley 错误处理广义化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21660695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com