I have a function that upon error (for example "timeout") is supposed to throw an error, which I catch at the end of the promise chain.
var createOrder = function (id) {
Utility.toggleProgressBar();
return $.ajax({
url: 'http://' + AppVar.ServerUrlWithPort + '/restapi/CreateOrder',
data: JSON.stringify({
'SessionId': AppVar.SessionId,
'Idrmtreq': id
}),
}).then(function (response) {
if (response.ResultCode === '0') {
return response;
} else {
throw new Error($.i18n('Error-RetrivingDataProblem'));
}
}).fail(function (x, t, m) {
if (t === "timeout") {
throw new Error($.i18n('Error-Timeout')); //code reaches here, where Chrome debugger says that this error was left Uncaught
//for the record, I checked whether the translation function could be the problem and it doesn't work even when I do 'throw "timeout";'
} else {
throw new Error($.i18n('Error-ConnError'))
}
}).catch(function (error) {
//error == {"readyState":0,"status":0,"statusText":"timeout"}
ErrorManager.displayError(error);
return;
}).always(function () {
Utility.toggleProgressBar();
})
}
To be specific, I'm experiencing a problem with the timeout. Code reaches to the throw. The throw I threw is actually left Uncaught, but something gets thrown. The Catch catches an error that contains this Object {"readyState":0,"status":0,"statusText":"timeout"}
.
I don't understand. What's throwing it?
Never use done
or fail
. They don't chain (and don't catch exceptions).
The fail()
call returns the original promise, which in your case means that the original error just falls through. You could use .catch()
instead, but notice that chaining .then(…).catch(…)
would make it to also handle the Error-RetrivingDataProblem. Instead you'll want to use
return $.ajax({
url: 'http://' + AppVar.ServerUrlWithPort + '/restapi/CreateOrder',
data: JSON.stringify({
'SessionId': AppVar.SessionId,
'Idrmtreq': id
}),
}).then(function (response) {
if (response.ResultCode === '0') {
return response;
} else {
throw new Error($.i18n('Error-RetrivingDataProblem'));
}
}, function(x, t, m) { /*
^^^ */
throw new Error($.i18n(t === "timeout" ? 'Error-Timeout' : 'Error-ConnError'));
}).catch(function (error) {
ErrorManager.displayError(error);
return;
})