title: error handling in Javascript promise
body: <p>I have some Javascript code doing some asyncronous stuff with some synchronouse post processing and then asyncronous stuff again (XHR -> parse XHR -> new XHR based on the first one). I don't get the error handling done:</p>
  
  <pre><code>/* API */
  function getFile(name) {
      return $.ajax({
          url: name + ".json"
      }).then(function(data) {
          return data.id
      }, handleError)
  }
  
  function handleError(errorObj) {
      if (errorObj.status) {
          return errorObj.status
      } else {
          return errorObj
      }
  }
  
  function myApiCall() {
      return getFile(1)
          .then(getFile, handleError)
          .then(getFile, handleError)
          .then(getFile, handleError)
          .then(getFile, handleError);
  }
  
  
  /* caller */
  
  function failFunction(status) {
      console.log("fail: ")
      console.log(status)
  }
  
  myApiCall().then(function(id) {
          console.log(id)
      }, failFunction)
  </code></pre>
  
  <p><code>1.json</code> looks something like this</p>
  
  <pre><code>{
      "id": "2"
  }
  </code></pre>
  
  <p>Just referencing the next file, the other ones are equivalent.</p>
  
  <p>Until here everything is fine (even I'm not sure if that's the best way to do errorhandling). If all files exist, the success function of the caller is called, otherwise the error function.</p>
  
  <p>But when having some errors in my synchronous code, everthing breaks</p>
  
  <pre><code>function getFile(name) {
      return $.ajax({
          url: name + ".json"
      }).then(function(data) {
          throw new Error(42) //       &lt;---------
      }, handleError)
  }
  </code></pre>
  
  <p>Now I get a console output</p>
  
  <pre><code>Error: 42
  </code></pre>
  
  <p>No further processing, caller is not informed.</p>
  
  <p>I tried something like that</p>
  
  <pre><code>function getFile(name) {
      return $.ajax({
          url: name + ".json"
      }).then(function(data) {
          throw new Error(42)
      }, handleError)
      .catch(handleError)
  }
  </code></pre>
  
  <p>But this doesn't make anything better. Mostly of all I get a <code>TypeError: $.ajax(...).then(...).catch is not a function</code></p>
  
  <p>How is error handling solved correct in this case?</p>