Override Backbone.Collection's `fetch()`
to allow for better error handling.

TODO: pull this into Backbone.sync instead..
only problem is clashing with other sync overrides
323476
function (options) {
			var collection = this;

			options = options || {};

			// Log a friendlier "No URL" message:
			if ( !collection.url ) {
				self.error('Cannot fetch() ' + collection.type + ' :: Collection has no URL function/property...');
				return;
			}

			// Override error handler to mixin an 'error' event
			var originalErrorHandler = options.error;
			var originalSuccessHandler = options.success;
			_.extend(options, {
				success: function (collection, xhr, options) {
					var args = Array.prototype.slice.call(arguments);

					// Null out `collection.syncing`
					collection.syncing = null;

					// Trigger original success handler if specified
					// on `fetch({success: function(){/*...*/}})`
					if (originalSuccessHandler) {
						return originalSuccessHandler.apply(collection, args);
					}
				},
				error: function (collection, xhr, options) {
					var args = Array.prototype.slice.call(arguments);

					// Null out `collection.syncing`
					collection.syncing = null;

					// If this is an "abort", ignore it- (state has already been taken care of)
					if ( xhr && xhr.statusText==='abort' ) return;

					// Set `collection.error` using the response from the fetch
					// (try json, then response text, then status code, then just default to `true`)
					collection.error =
						( xhr && xhr.responseJSON ) ? xhr.responseJSON :
						( xhr && xhr.responseText ) ? xhr.responseText :
						true;


					// Call `afterError()`
					collection.afterError.apply(collection,args);

					// Trigger original error handler if specified
					// on `fetch({error: function(){/*...*/}})`
					if (originalErrorHandler) {
						return originalErrorHandler.apply(collection, args);
					}
				}
			});

			// Null out `collection.error`
			collection.error = null;

			// If `fetch` is already in progress, cancel it
			// and fire off a new one.
			if (collection.syncing) {
				self.log('Aborting running `fetch()` in order to start a new `fetch()`...');
				collection.syncing.abort();
			}

			// Call original `fetch()` using our monkey-patched options
			var xhr = collection._fetch(options);

			// Set `collection.syncing` to the XHR object in use
			collection.syncing = xhr;

			// Return the XHR object to maintain original `Backbone.Collection.fetch()` API
			return xhr;
		}
1354699
def fetchmany(self, count=None):
        
        if count is None:
            count = self.arraysize
        if count == 0:
            return self.fetchall()
        result = []
        for i in range(count):
            try:
                result.append(self.next())
            except StopIteration:
                pass
        return result
132937
function (context, callback) {
            var self = this,
                model;

            flow()
                .seq("collection", function (cb) {
                    self._findCollection(context, cb, false);
                })
                .seq(function (cb) {
                    var modelFactory = self._getModelFactory();
                    var id = self.$resourceId;
                    id = modelFactory.prototype.convertIdentifier(id);
                    model = this.vars.collection.createItem(id);

                    if (context) {
                        // TODO: build options
                    }
                    self._beforeModelFetch(model, context, cb);
                })
                .seq(function (cb) {
                    model.fetch(null, cb);
                })
                .seq(function () {
                    // fetch hrefs for all sub models and sub collections
                    self._fetchAllHrefsForModel(model, context);
                })
                .exec(function (err) {
                    if (!err) {
                        var processor = self.$restHandler.$restDataSource.getProcessorForModel(model);

                        var body = JSON.stringify(processor.compose(model, "GET", self._getCompositionOptions(context))),
                            response = context.response;

                        response.writeHead(200, {
                            'Content-Type': 'application/json'
                        });

                        response.write(body);
                        response.end();

                        callback(null);
                    } else {
                        if (!(err instanceof HttpError)) {
                            var statusCode = 500;
                            if (err === DataSource.ERROR.NOT_FOUND) {
                                statusCode = 404;
                            }
                            err = new HttpError(err, statusCode);
                        }
                        callback(err);
                    }

                });
        }
1005078
function(cursor, callback) {
    groupedDelta = {};

    async.series([
      (cb) => {
        logger.info('Fetching delta', {category: 'sync-remote-delta'});

        fetchDelta({cursor}, (err, newCursor) => {
          if(err) return cb(err);

          cb(null, newCursor);
        });
      },
      (cb) => {
        logger.info('Applying collections which need to be redownloaded', {category: 'sync-remote-delta'});

        syncDb.find({$and: [{directory: true}, {downloadOriginal: true}]}, (err, syncedNodes) => {
          if(err) return cb(err);
          if(!syncedNodes) return cb(null);

          async.map(syncedNodes, (syncedNode, mapCb) => {
            if(!syncedNode.remoteId) mapCb(null);

            fetchDelta({id: syncedNode.remoteId}, mapCb);
          }, cb);
        });
      }
    ], (err, results) => {
      logger.info('getDelta ended', {category: 'sync-remote-delta'});

      callback(err, results[0]);
    });
  }
668516
function wrappingFetch({ url, method, data }, optionsArg) {
    let requestStatus = createRequestStatus();
    // Here we are using destruct to filter properties we do not want to give to fetch.
    // CORS and isCORS are useless legacy code, xhrErrors is used only in error parsing
    // eslint-disable-next-line no-unused-vars
    let { CORS, isCORS, xhrErrors, ...config } = configGetter();
    const { noStringify, ...options } = optionsArg || {};
    const reqOptions = merge({ headers: {} }, config, options, { method, body: noStringify ? data : JSON.stringify(data) });
    //By default, add json content-type
    if (!reqOptions.noContentType && !reqOptions.headers['Content-Type']) {
        reqOptions.headers['Content-Type'] = 'application/json';
    }
    // Set the requesting as pending
    updateRequestStatus({ id: requestStatus.id, status: 'pending' });
    // Do the request
    return fetch(url, reqOptions)
        // Catch the possible TypeError from fetch
        .catch(error => {
            updateRequestStatus({ id: requestStatus.id, status: 'error' });
            return Promise.reject({ globalErrors: [error] });
        }).then(response => {
            updateRequestStatus({ id: requestStatus.id, status: response.ok ? 'success' : 'error' });
            const contentType = response.headers.get('content-type');
            return getResponseContent(response, reqOptions.dataType ? reqOptions.dataType : contentType && contentType.includes('application/json') ? 'json' : 'text');
        }).catch(data => {
            checkErrors(data, xhrErrors);
            return Promise.reject(data);
        });
}
148154
function catchpath (req, res, pathmatch, callback, templateReader) {
  getQueries(req, function gotQueries(err) {
    if (err != null) {
      log('While getting queries for ' + req.uri + ':\n'
        + err
        , 'error');
    } else {
      // params: template parameters (JSON-serializable).
      callback(req.query, pathmatch, function end (params, options) {
        options = options || {};
        var templates = options.template || pathmatch[0];
        var reader = options.reader || templateReader;
        if (Object(options.string) instanceof String) {
          templates = [streamFromString(options.string)];
        } else if (Object(params) instanceof String) {
          templates = [streamFromString(params)];
        } else if (!Array.isArray(templates)) {
          templates = [templates];
        }
        if (!res.getHeader('Content-Type')  // Allow overriding.
            && (Object(templates[0]) instanceof String)) {
          res.mime(p.extname(templates[0]).slice(1));
        }
        for (var i = 0; i < templates.length; i++) {
          if (Object(templates[i]) instanceof String) {
            // `templates[i]` is a string path for a file.
            var templatePath = p.join(req.server.documentRoot, templates[i]);
            templates[i] = fs.createReadStream(templatePath);
          }
        }

        var template = concatStreams(templates);

        template.on('error', function(err) {
          log(err.stack, 'error');
          res.end('Not Found\n');
        });

        if (params === null || reader === null) {
          // No data was given. Same behaviour as static.
          template.pipe(res);
        } else {
          reader(template, res, params, function errorcb(err) {
            if (err) {
              log(err.stack, 'error');
              res.end('Not Found\n');
            }
          });
        }
      }, req.ask);
    }
  });
}
1307958
function fetch( $template = false, $extraParameters = false, $returnResourceData = false )
    {
        $this->resetErrorLog();
        // Reset fetch list when a new fetch is started
        $this->TemplateFetchList = array();

        eZDebug::accumulatorStart( 'template_total' );
        eZDebug::accumulatorStart( 'template_load', 'template_total', 'Template load' );
        $root = null;
        if ( is_string( $template ) )
        {
            $resourceData = $this->loadURIRoot( $template, true, $extraParameters );
            if ( $resourceData and
                 $resourceData['root-node'] !== null )
                $root =& $resourceData['root-node'];
        }
        eZDebug::accumulatorStop( 'template_load' );
        if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
        {
            $savedLocale = setlocale( LC_CTYPE, null );
            setlocale( LC_CTYPE, $resourceData['locales'] );
        }

        $text = "";

        if ( $root !== null or
             $resourceData['compiled-template'] )
        {
            if ( $this->ShowDetails )
                eZDebug::addTimingPoint( "Process" );
            eZDebug::accumulatorStart( 'template_processing', 'template_total', 'Template processing' );

            $templateCompilationUsed = false;
            if ( $resourceData['compiled-template'] )
            {
                $textElements = array();
                if ( $this->executeCompiledTemplate( $resourceData, $textElements, "", "", $extraParameters ) )
                {
                    $text = implode( '', $textElements );
                    $templateCompilationUsed = true;
                }
            }
            if ( !$templateCompilationUsed )
            {
                if ( eZTemplate::isDebugEnabled() )
                {
                    $fname = $resourceData['template-filename'];
                    eZDebug::writeDebug( "FETCH START URI: $template, $fname" );
                }
                $this->process( $root, $text, "", "" );
                if ( eZTemplate::isDebugEnabled() )
                    eZDebug::writeDebug( "FETCH END URI: $template, $fname" );
            }

            eZDebug::accumulatorStop( 'template_processing' );
            if ( $this->ShowDetails )
                eZDebug::addTimingPoint( "Process done" );
        }

        eZDebug::accumulatorStop( 'template_total' );

        if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
        {
            setlocale( LC_CTYPE, $savedLocale );
        }

        if ( $returnResourceData )
        {
            $resourceData['result_text'] = $text;
            return $resourceData;
        }
        return $text;
    }
1310337
function handleError(error, ignoreError) {
    appStore.setLoading(false)
    let reason

    if (error.response) {
        reason = handleResponseError(error)
    } else if (error.status >= 200 && error.status < 300) {
        reason = handleServiceError(error)
    } else {
        reason = handleRequestError(error)
    }

    if (ignoreError !== true) {
        appStore.setError(reason)
    }

    return Promise.reject(reason)
}
1017229
function(options) {
      options = options ? _.extend({}, options) : {};
      if (options.parse === void 0) options.parse = true;
      var success = options.success;
      var collection = this;
      options.success = function(resp) {
        var method = options.reset ? 'reset' : 'set';
        collection[method](resp, options);
        if (success) success(collection, resp, options);
        collection.trigger('sync', collection, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    }
827836
function fetchCollectionAttributeHTTPInput( $collection, $collectionAttribute, $http, $base, $contentObjectAttribute )
    {
        if ( $http->hasPostVariable( $base . "_data_integer_" . $contentObjectAttribute->attribute( "id" ) ) )
        {
            $data = $http->postVariable( $base . "_data_integer_" . $contentObjectAttribute->attribute( "id" ) );
            $data = trim( $data ) != '' ? $data : null;
            $data = str_replace(" ", "", $data);
            $collectionAttribute->setAttribute( "data_int", $data );
            return true;
        }
        return false;
    }
490054
function(error) {
		var that = this,
			param = this.chainParameter,
			stopPointer = {},
			utils = {
				stop: null,
				url: this.scraper.url,
				scraper: this,
				params: param,
				lastReturn: undefined
			},
			keep = true;
		this.chainParameter = null;

		if (error) {
			this.errorCallback(error, utils);
			this.doneCallback(utils);
			return;
		}

		async.eachSeries(this.promises, function dispatcher(fn, callback) {
			var done = function(err, lastReturn) {
				utils.lastReturn = lastReturn;
				if (err === stopPointer) {
					keep = false;
					callback(err);
				} else if (err) {
					callback(err);
				} else if (keep) {
					callback();
				}
			};
			utils.stop = function() {
				done(stopPointer, null);
			};

			try {
				fn.call(that, done, utils);
			} catch (err) {
				done(err, null);
			}
		}, function(err) {
			utils.stop = null;
			if (err && err !== stopPointer) {
				that.errorCallback(err, utils);
			}
			that.doneCallback(utils.lastReturn, utils);
			that.scraper.close();
		});
	}
1221196
function wrap_sync(fn) {
  return function (params) {
    var val = fn(params);
    if (val && !isPromise(val)) throw val;
    return val;
  };
}
803839
function(options) {
      options = options ? _.clone(options) : {};
      var model = this;
      var success = options.success;

      var triggerDestroy = function() {
        model.trigger('destroy', model, model.collection, options);
      };

      if (this.isNew()) {
        triggerDestroy();
        return false;
      }

      options.success = function(resp) {
        if (options.wait) triggerDestroy();
        if (success) {
          success(model, resp);
        } else {
          model.trigger('sync', model, resp, options);
        }
      };

      options.error = Backbone.wrapError(options.error, model, options);
      var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options);
      if (!options.wait) triggerDestroy();
      return xhr;
    }
1356921
function(options) {
      options = options ? _.clone(options) : {};
      if (options.parse === void 0) options.parse = true;
      var model = this;
      var success = options.success;
      options.success = function(resp) {
        if (!model.set(model.parse(resp, options), options)) return false;
        if (success) success(model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    }
1362498
def sync_fetch(request, method, default_headers=None,
               httpclient=None, **kwargs):
    
    updated_request = make_request(request, method, default_headers, **kwargs)
    if not httpclient:
        httpclient = HTTPClient()
    rsp = httpclient.fetch(updated_request)
    return parse_response(rsp)
985409
def make_fetch_func(base_url, async, **kwargs):
    
    if async:
        client = AsyncHTTPClient(force_instance=True, defaults=kwargs)
        return partial(async_fetch, httpclient=client)
    else:
        client = HTTPClient(force_instance=True, defaults=kwargs)
        return partial(sync_fetch, httpclient=client)
84094
function (err, collection) {
                if (err) {
                    return callback(err);
                }

                // ensure that the collection option is present before starting a run
                if (!_.isObject(collection)) {
                    return callback(new Error(COLLECTION_LOAD_ERROR_MESSAGE));
                }

                // ensure that the collection reference is an SDK instance
                // @todo - should this be handled by config loaders?
                collection = new Collection(Collection.isCollection(collection) ?
                    // if the option contain an instance of collection, we simply clone it for future use
                    // create a collection in case it is not one. user can send v2 JSON as a source and that will be
                    // converted to a collection
                    collection.toJSON() : collection);

                callback(null, collection);
            }