【问题标题】:Android volley: how to handle the error responseAndroid volley:如何处理错误响应
【发布时间】:2015-10-07 03:35:07
【问题描述】:

我实现了一个带有 volley 库的 android 应用程序来连接我的数据库。与“获取”和“发布”请求的连接有效,但服务器响应无效。 发生这种情况是因为错误响应会自动捕获错误(例如,我的服务器响应代码为 201 表示登录成功,但 volley untersand it like error)。

我覆盖了 Request 类中的 parseNetworkError:

 @Override
    protected VolleyError parseNetworkError(VolleyError volleyError) {
        String parsed;
        NetworkResponse networkResponse = volleyError.networkResponse;
        if(networkResponse != null && networkResponse.data != null) {
            try {
                parsed = new String(networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers));
            } catch (UnsupportedEncodingException var4) {
                parsed = new String(networkResponse.data);
            }
            NetworkResponse response = new NetworkResponse(networkResponse.data);
            Response<String> parsedResponse;
            switch(response.statusCode){
                case 204:                        
                    ...
                case 401:
                    ...
                default:
                    return volleyError;
            }
        }

        return super.parseNetworkError(volleyError);
    }

问题是 VolleyError。此类扩展 Exception 并且不包含信息(代码错误)。

我该如何解决这个问题?

【问题讨论】:

标签: android exception android-volley


【解决方案1】:

你可以这样处理

@Override
public void onErrorResponse(VolleyError error) {
    // Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
    // For AuthFailure, you can re login with user credentials.
    // In this case you can check how client is forming the api and debug accordingly.
    // For ServerError 5xx, you can do retry or handle accordingly.
    if( error instanceof NetworkError) {
    //handle your network error here.
    } else if( error instanceof ServerError) {
    //handle if server error occurs with 5** status code
    } else if( error instanceof AuthFailureError) {
    //handle if authFailure occurs.This is generally because of invalid credentials
    } else if( error instanceof ParseError) {
    //handle if the volley is unable to parse the response data.
    } else if( error instanceof NoConnectionError) {
    //handle if no connection is occurred
    } else if( error instanceof TimeoutError) {
    //handle if socket time out is occurred.
    }

}

【讨论】:

  • ClientError 在 volley 库中找不到类。 ?
【解决方案2】:
        public void onErrorResponse(VolleyError error) {
            String message=null;
            if(error instanceof NetworkError)
            {
                message = "Cannot connect to Internet...Please check your connection!";
                Toast.makeText(ScanQrCodeActivity.this, message, Toast.LENGTH_SHORT).show();
            }
            else if(error instanceof ServerError)
            {
                message = "The server could not be found. Please try again after some time!!";
                Toast.makeText(ScanQrCodeActivity.this, message, Toast.LENGTH_SHORT).show();
            }
            else if (error instanceof ParseError) {
                message = "Parsing error! Please try again after some time!!";
                Toast.makeText(ScanQrCodeActivity.this, message, Toast.LENGTH_SHORT).show();
            }

            swipeRefreshLayout.setRefreshing(false);
            HideSwipeDialog();

        }

在 Volley 响应中显示错误的最佳方式,但不要将直接消息发送给最终用户有创意并显示类似“等待我们连接到服务器的那一刻”的消息

【讨论】:

    【解决方案3】:

    这是我在项目中使用的:

        @Override
        public void onErrorResponse(VolleyError error) {
            if(error instanceof NoConnectionError){
                ConnectivityManager cm = (ConnectivityManager)mContext
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetwork = null;
                if (cm != null) {
                    activeNetwork = cm.getActiveNetworkInfo();
                }
                if(activeNetwork != null && activeNetwork.isConnectedOrConnecting()){
                    Toast.makeText(getActivity(), "Server is not connected to internet.",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "Your device is not connected to internet.",
                            Toast.LENGTH_SHORT).show();
                }
            } else if (error instanceof NetworkError || error.getCause() instanceof ConnectException 
                    || (error.getCause().getMessage() != null 
                    && error.getCause().getMessage().contains("connection"))){
                Toast.makeText(getActivity(), "Your device is not connected to internet.", 
                        Toast.LENGTH_SHORT).show();
            } else if (error.getCause() instanceof MalformedURLException){
                Toast.makeText(getActivity(), "Bad Request.", Toast.LENGTH_SHORT).show();
            } else if (error instanceof ParseError || error.getCause() instanceof IllegalStateException
                    || error.getCause() instanceof JSONException
                    || error.getCause() instanceof XmlPullParserException){
                Toast.makeText(getActivity(), "Parse Error (because of invalid json or xml).", 
                        Toast.LENGTH_SHORT).show();
            } else if (error.getCause() instanceof OutOfMemoryError){
                Toast.makeText(getActivity(), "Out Of Memory Error.", Toast.LENGTH_SHORT).show();
            }else if (error instanceof AuthFailureError){
                Toast.makeText(getActivity(), "server couldn't find the authenticated request.", 
                        Toast.LENGTH_SHORT).show();
            } else if (error instanceof ServerError || error.getCause() instanceof ServerError) {
                Toast.makeText(getActivity(), "Server is not responding.", Toast.LENGTH_SHORT).show();
            }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"))) {
                Toast.makeText(getActivity(), "Connection timeout error", 
                        Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity(), "An unknown error occurred.", 
                        Toast.LENGTH_SHORT).show();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多