title: Re-call Backbone.Sync method after error callback
body: <p>I am working on an application where if our Bearer token has expired and we get a 401 back from the server. We want to call an endpoint <code>/api/newToken</code> and set that new bearer token to the cookie (which is later added to the headers) and then re call the URL that was being called when the error (401 status) occurred.</p>
  
  <p>We overwrote the backbone sync method</p>
  
  <pre><code>var sync_mixin = {
          // `preSync` is a useful hook from which events can be published,
          //      and options / model may be modified.
          preSync: function (method, model, options) {},
  
          // override sync to:
          //  - call preSync first
          //  - because tastypie and backbone disagree on whether delete should have trailing slash
          sync: function (method, model, options) {
              model.preSync(method, model, options);
              options = options || {};
              options.headers = getAuthHeaders()
  
              // Add trailing slash to backbone model views
              var _url = _.isFunction(model.url) ?  model.url() : model.url;
              // Missing the case where there is a query string on a detail view here: /v7.0/&lt;resource&gt;/&lt;id&gt;?key=val
              _url += _url.charAt(_url.length - 1) == '/' || _url.indexOf('?') != -1 ? '' : '/';
  
              options = _.extend(options, {
                  url: _url,
                  model: model
              });
  
              if (method.toLowerCase() === 'delete') {
                  if (!options.url) {
                      options.url = _.result(model, 'url').replace(/\/$/, "") + '/';
                  }
              }
  
              return Backbone.sync.apply(this, arguments);
          }
      };
  
      Backbone.Model = Backbone.Model.extend(sync_mixin);
  </code></pre>
  
  <p>Ideally I want to handle the error in once place (and not within each model file). What I am trying to accomplish is when I get the error on sync, call the api endpoint get the new token, set it to the cookie and re call the original sync method with the new cookie as the token. Here is what I have tried, but I am running into maximum call stack errors. I added this code inside the sync function above</p>
  
  <pre><code>            options.error = function(xhr, status, thrown) {
                if(xhr.status === 401 || xhr.status === 403){
                    $.cookies.set("auth-token", '6fe36b69cdac549339850a5aa2f148b470dc2e0e');
                    Backbone.sync.apply(this.model, arguments);
                }
              }
  </code></pre>
  
  <p>Any suggestions on how to resolve this issue? I can get anything else that is needed.</p>