salah3x
salah3x

Reputation: 231

Handle ajax errors and execute the promise chain

I'm trying to provide a fallback for the failed ajax requests. I want a global solution so I won't have to change every call in the code.

I tried providing an error handler to ajaxSetup, but the problem is I couldn't execute the chained callbacks.

$.ajaxSetup({
  error: function() {
    console.error('Error occurred')
    return $.getJSON('https://jsonplaceholder.typicode.com/todos/1')
  }
})

$.getJSON('https://jsonplaceholder.typicode.com/todos/0') // Id doesn't exist
  .then(todo => console.log(todo))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Expected output

Error occurred
{
  "id": 1,
  "title": "...",
  ...
}

Upvotes: 0

Views: 128

Answers (1)

fefoweb
fefoweb

Reputation: 61

From jQuery 3.0 the callback method accepted are: done, always, fail. So, i would have called the callback fail and in the inner, i resend the ajax call wrapped into a properly function with dynamic id

const submit = (id) => {
      const xhr = $.getJSON(`https://jsonplaceholder.typicode.com/todos/${id}`)
         .done(todo => console.log(todo))
         .fail(err => { console.error(err); submit(id++); });
};

submit(0);

Upvotes: 1

Related Questions