检查网络并处理空错误对象

时间:2015-05-14 20:38:45

标签: javascript angularjs cordova parse-platform ionic-framework

我使用Parse.com作为Ionic Framework App的后端,这意味着我必须监控网络活动。我可以使用此guide在线/离线处理。但是,我需要在每次通话时使用更多“app wide”解决方案检查。当没有网络时我正在收到错误,因为来自服务器的responsenull导致以下错误:

Error: null is not an object (evaluating 'response.error')

我的问题有两个:

  1. 是否可以创建一个网络factory / service,我可以将其注入我的ParseFactory,以检查并通知用户他们的网络不足。

  2. 在此代码中处理null响应对象:

    ParseFactory.provider('Programme/').get($stateParams.loadProgramme).success (function(data){
     // do something with success...
     }).error(function(response){
     $rootScope.$emit('errorEvent',
        {"message" : "Unable to load Programme. Please check your  connection", "errorObject": response.error} 
        );
    });
    
  3. 我的Parse呼叫工厂如下:

    .factory('ParseFactory',['$http','PARSE_CREDENTIALS',function($http,PARSE_CREDENTIALS){
    var baseUrl = 'https://api.parse.com/1/classes/';
        return {
            provider:function(type, queryParam, queryValue) {
                console.log(queryValue);
                whereQuery = {}
                whereQuery[queryParam] = queryValue;
    
                var masterQuery = {'userId': masterKey};
                return {
                    getAll:function(){
                        return $http.get(getUrl(type),getParams(whereQuery));
                    },
                    getMasters:function(){
                        return $http.get(getUrl(type),getParams(masterQuery));
                    },
                    get:function(id){
                        return $http.get(getUrl(type)+id,getParams());
                    },
                    create:function(data){
                        return $http.post(getUrl(type),data,getParams());
                    },
                    edit:function(id,data){
                        return $http.put(getUrl(type)+id,data,getParams());
                    },
                    delete:function(id){
                        return $http.delete(getUrl(type)+id,getParams());
                    }
                }
                function getUrl(type) {
                    return baseUrl+type;
                }
    
                function getParams(user) {
                    return {
                            timeout : 5000,
                            headers:{
                                'X-Parse-Application-Id': PARSE_CREDENTIALS.APP_ID,
                                'X-Parse-REST-API-Key':PARSE_CREDENTIALS.REST_API_KEY,
                                'X-Parse-Session-Token': Parse.User.current()._sessionToken,
                                'Content-Type':'application/json'
                            },
                            params: { 
                            where: user,
                             // limit: 2,
                             // count: 1
                             // include: "something"
                        }      
                    }    
                }
            }
        }
    }])
    

1 个答案:

答案 0 :(得分:1)

使用$http interceptor。使用$ http的所有请求都通过拦截器传递,因此通过使用拦截器,您可以对成功或不成功的请求和响应应用全局处理。

例如,如果网络连接不可用,此拦截器将取消请求,并在收到空响应时发出事件:

app.factory('networkActivityInterceptor', function($rootScope, $q, networkMonitorService) {
  return {
    'request': function(config) {
      var canceller = $q.defer();
      config.timeout = canceller.promise;

      if (!networkMonitorService.hasNetworkConnection()) {
        // cancels the request if there is no network connection
        canceller.resolve();
      }

      // otherwise, let the request go through as normal
      return config;
    },

    'response': function(response) {
      // handle a null/empty response
      if (!response.data) {
        $rootScope.$emit('errorEvent', {
          message: 'Unable to load...',
          errorObject: response.error
        });
      }

      return response;
    },

    'responseError': function(response) {
      // the response handling above could also be done in the responseError
      // handler which is hit when an error HTTP code is returned. (example: 404, 500)
      // this depends on what your server is configured to return.

      // note that in a responseError handler you must return a rejected promise
      // (i.e. return $q.reject(response);)
    }
  };
});

networkMonitorService.hasNetworkConnection()替换为您应用的网络活动逻辑。