Search code examples
javascriptjqueryajaxbackbone.jschaplinjs

$(document).ajaxError is not firing on 401


We have an error handler to post the message.

 $(document).ajaxError(function (e, xhr, options) {
  window.postMessage(....);  
});

One of the fetch call is returning 401

this.fetch = function(url) {
return fetch(url, { 
  }
}).then(function(response) {
  return response.json();
})

When I check the response the status is 401 but the response.json() is throwing " Uncaught (in promise) SyntaxError: Unexpected end of JSON input. " Because of this, the ajaxError is not firing.

Expected Behaviour: I want the document.ajaxError to post the message if I don't get the status 200 from the fetch call.

We have an wrapper.js which has overriding function

 window.fetch = (function(arg) {


 }(window.fetch)

Can I catch this exceptions globally inside of this function?


Solution

  • As per the comments I wasn't able to do it on the ajaxError handler as its not originating from the jquery. I was able to do it inside the Window.fetch wrapper

     window.fetch = (function (original)) {
      ...............
    
      return original.apply(this, args).then(function (response)) {
    
          if(response.status !== 200)
           {
               window.postMessage({ event_type: 'request:failed', status: response.status); 
           }   
       }
    }