I have Javascript code that does some asynchronous things with some sort of synchronous mail processing and then again asynchronous (XHR -> parsing XHR -> new XHR based on the first). I do not do error handling:
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); } function failFunction(status) { console.log("fail: ") console.log(status) } myApiCall().then(function(id) { console.log(id) }, failFunction)
1.json looks something like this:
{ "id": "2" }
Just refers to the following file, others are equivalent.
So far, everything is fine here (even I'm not sure if this is the best way to do error handling). If all files exist, the caller's success function is called; otherwise, the error function.
But if there are some errors in my synchronous code everthing breaks
function getFile(name) { return $.ajax({ url: name + ".json" }).then(function(data) { throw new Error(42)
Now I get console output
Error: 42
No further processing, the caller is not informed.
I tried something like this
function getFile(name) { return $.ajax({ url: name + ".json" }).then(function(data) { throw new Error(42) }, handleError) .catch(handleError) }
But it does nothing better. Basically I get TypeError: $.ajax(...).then(...).catch is not a function
How is error handling correct in this case?