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:
/* 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)
1.json looks something like this
{
"id": "2"
}
Just referencing the next file, the other ones are equivalent.
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.
But when having some errors in my synchronous code, everthing breaks
function getFile(name) {
return $.ajax({
url: name + ".json"
}).then(function(data) {
throw new Error(42) // <---------
}, handleError)
}
Now I get a console output
Error: 42
No further processing, caller is not informed.
I tried something like that
function getFile(name) {
return $.ajax({
url: name + ".json"
}).then(function(data) {
throw new Error(42)
}, handleError)
.catch(handleError)
}
But this doesn't make anything better. Mostly of all I get a TypeError: $.ajax(...).then(...).catch is not a function
How is error handling solved correct in this case?