SyntaxStudy
Sign Up
jQuery Error Handling in Deferred Chains
jQuery Intermediate 4 min read

Error Handling in Deferred Chains

Error Handling

A single .fail() at the end of a chain catches any rejection. Use .then(success, failure) to handle errors at each step individually.

Example
$.getJSON("/api/step1")
  .then(function(data) {
    if (!data.ok) return $.Deferred().reject("Step 1 failed");
    return $.getJSON("/api/step2?id=" + data.id);
  })
  .then(function(result) {
    render(result);
  })
  .fail(function(err) {
    showError("Operation failed: " + err);
  });
Pro Tip

Returning a rejected Deferred from .then() propagates the failure to the .fail() handler.