Check network and handle empty error object

I am using Parse.com as a backend for an Ionic Framework App which means I have to monitor the network activity. I can handle online / offline by using this guide. However, I need a more 'app wide' solution checks on each call. I'm currently getting errors when there is no network as the response from the server is null causing the following error:

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

My question is two fold:

  1. Is it possible to create a network factory / service that I can inject into my ParseFactory to check and notify the user that their network is insufficient.

  2. Handle a null response object in this code:

    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} 
        );
    });
    

My Factory for Parse calls is below:

.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"
                    }      
                }    
            }
        }
    }
}])

Use a $http interceptor. All requests using $http are passed through interceptors, so by using interceptors you can apply global handling for successful or unsuccessful requests and responses.

For example, this interceptor cancels a request if the network connection is not available and emits an event when an empty response is received:

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);)
    }
  };
});

Substitute networkMonitorService.hasNetworkConnection() for your app's network activity logic.