Currently I've got this:
$http({
method: 'POST',
url: 'http://api-endpoint/somescript/',
data: formData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
console.log(response);
});
If the script on the other end works out ok, then
gets called. However, let's say the script on the server end has some sort of error that's not properly caught. If I make up an error by tossing in some garbage call like asdfasdf()
, the then
function isn't called, and instead I get this in the browser console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://api-endpoint/somescript/. (Reason: CORS
header 'Access-Control-Allow-Origin' missing).
How do I catch this in the Angular code so I can handle it in a user-friendly manner?
EDIT: This is not a duplicate, as it is specific to Angular.
The
$q.then()
method accepts three function parameters, the first being the handler for a successful callbacks, the second being for errors, and the third being for notify.$http
leverages$q
behind the scenes so thisthenable
should behave like the documentation suggests.To handle errors in the above code, just toss in an additional function for error handling as such:
Feel free to browse the $q documentation, specifically The Promise API, for additional details.