Angular logs HTTP error before handling it - javascript

I have the following mechanism (ignore the simplicity for the moment please) when a user clicks on a button on a dead simple login form:
$scope.login = function () {
$http.post('/rest/authenticate', {
userName: $scope.userName,
password: $scope.password
}).
success(function (data, status, headers, config) {
//handle success, etc
}).
error(function (data, status, headers, config) {
//hanlde errors, etc
});
};
The method is calling a REST service that could return a String as an answer if the proper credentials are provided or an error (400, 401) if they are not good. The success method gets executed when the good user/pass is given and the error function also executes if the REST call returns some HTTP error.
My problem is that if any kind of error happens, BEFORE the error method gets executed, angular displays the error in the browser console like this:
POST http://server.address/rest/authenticate 400 (Bad Request)
This originates from angular.js (line 8113):
xhr.send(post || null);
It even displays it before a http interceptor's 'responseError' method. Using non-compressed angular version 1.2.14
How can I turn this unnecessary logging off?

zeroflagL's comment is valid and I found no solution to this "issue"

Related

AngularJS - trouble with $http's success() and error() not being called properly

I am working on this code and I have a really weird issue. I am using AngularJS $http request, and trying to run a success or error afterwards. I am currently getting a 404 from the server (the client says) but the server isn't barfing up a 404 (in fact it says it sent a 200 response).
This $http post doesn't hit either the 'success' or 'error' handlers and I don't know what to do for debugging it.
All other functions using RequestService work perfectly.
var refreshBusinesses = function() {
console.log("refreshBusinesses");
RequestService.post('user/managed_businesses', {}).then(function(businesses){
console.log('got busineses ', businesses)
$scope.businesses = businesses
}, function(error){
console.log("ERROR!");
$scope.error = error.message;
console.log('business refresh error ', error)
})
}
Most probably your service RequestService does not handle promise properly. I believe it is a wrapper around angular's $http. If so, probably it does not reject promise on error, but simply returns some value.
So to solve it check your RequestService that it handles error situation properly:
$http.post('url', data).then(
function(res) {
return res;
},
function(error) {
var deferred = $q.defer();
return deferred.reject(error);
});
$q docs can be found here https://docs.angularjs.org/api/ng/service/$q

Ember -- JSON API Adapter Error Handling

I want to take a specific action when an API request results in a 404 error. I've read that the appropriated way to do this would be handling the error in the application adapter like below:
handleResponse: function(status, headers, payload){
if(status === 404 && payload.errors){
//handle error
}
return this._super(...arguments);
}
The problem is, as soon as I set up the adapter, it won't finish loading the page so I can handle the error on the page itself. Instead, it automatically takes me to some error route that just says "Adapter error". How can I stop/override this behaviour?
Turns out I needed to adjust the handleResponse hook in the application adapter to pass the new requestData parameter to the super method.
handleResponse (status, headers, payload, requestData) {
return this._super(status, headers, payload, requestData);
},
Then I just changed the first line of the code in my question from
handleResponse: function(status, headers, payload) {
to
handleResponse: function(status, headers, payload, requestData) {
I was then able to catch and handle the error
Perhaps you could handle it on a request basis like below:
return this.get('store').find('user', userId).then((user) => {
this.set('user', user);
}).catch((reason) => {
var possible404 = reason.errors.filterBy('status','404');
if(possible404.length !== 0) {
// Handle 404 error
}
});
Although this is not the solution that you wanted, this alternative will allow you to customize more. By the way, the automatic behavior seems to be the application-error substates kicking in on 404, so give it a read if you want to override the behavior.

Handle AngularJS errors while loading template file

I create an app with requirement of template files being in two folders - first is available without restrictions and second is available only for logged in users.
Things are complicating when somebody refresh the page and session expire before. Angular throws error (e.g. 401) in console while loading template file which I want to avoid. Is there a way to catch that event and access response status to for e.g. redirect the page?
For your case, we can catch the error and redirect to a page with the help of $location.url(). Here is the concept. Now i have a controller and in that, i have success function and error function. Whenever we get an error, the error function will run and we can pass the link of the page you want to redirect.
$http.get(url,[params])
.success(function(data, status, headers, config){
// bind your data to scope
})
.error(function(data, status, headers, config) {
$location.url('/404');
});
By the use of $routeProvider, you can configure the function something like
this :
$routeProvider
.when('/404', {
templateUrl: '404.html',
controller: 'yourcontroller'
});
And you can see the description for $location.url() here
Hope it works

AngularJS HTTP Call / Response

This is probably something very simple but I am having some problem making an HTTP GET request, getting the data back, and attaching it onto the javascript global window variable.
Simple HTTP Call:
$http.get("production/dashboard?dashboard_type=A").success((data) ->
$scope.pods = data;
window.pods = $scope.pods.to_json;
window.type = 'A';
alert(window.pods)
alert(window.type)
alert "success1"
return
).error (data, status, headers, config) ->
return
Upon execution, I am getting:
1. Alert("undefined")
2. Alert("A")
I thought that the promise of the http request will get resolved when the response returns?
I checked the Network tab and there is indeed JSON data being sent back as the response to the request.
I must be missing something simple...
$http.get("production/dashboard?dashboard_type=A")
.success(function(data) {
$scope.pods = data;
window.pods = $scope.pods;
window.type = 'A';
alert(window.pods);
alert(window.type);
alert("success1");
return
}).error (function(data, status, headers, config){
return;
});
This is assuming it has access to the window where your code is. Is this wrapped in a module and controller?
As we need json data to get from $http.. Trying putting .json like below.
$http.get('/products.json')
Regarding your another issue.. you might get a hint with this link AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

Angular $http error callback response is always undefined

I am having issues trying to gracefully handle $http errors. I am looping over a list of servers to make API calls to for status. The calls that complete successfully for perfectly. The ones that fail are not giving me access to the error information. It is always undefined. Here is the code snippet:
angular.forEach($scope.servers, function (server) {
// blank out results first
server.statusResults = {};
$http.jsonp(server.url + '/api/system/status?callback=JSON_CALLBACK', {headers: { 'APP-API-Key': server.apiKey }}).
success(function (data, status, headers, config) {
server.statusResults = data;
}).
error(function (data, status, headers, config) {
// data is always undefined here when there is an error
console.error('Error fetching feed:', data);
});
}
);
The console output shows the correct 401 error (which I didn't output) and my console error message (which I did output) with an undefined data object.
GET https://server_address/api/system/status?callback=angular.callbacks._1 401 (Unauthorized) angular.min.js:104
Error fetching feed: undefined
What I am trying to do is NOT have Angular display the 401 in the log, and instead I will display it in a graceful way. However since data is undefined I have no way of accessing the information.
I am new to AngularJS, but my example closely matches other examples I've found in the documentation.
I've also tried using $resource instead of the $http and got the exact same problem.
var statusResource = $resource(server.url + '/api/system/status', {alt: 'json', callback: 'JSON_CALLBACK'},
{ status: {method: 'JSONP'}, isArray: false, headers: { 'APP-API-Key': server.apiKey } });
// make status API call
statusResource.status({}, function (data) {
server.statusResults = data;
}, function (err) {
// data is always undefined here when there is an error
console.log(err);
});
I'm probably doing something obviously wrong, but I'm not sure what else to try.
Per the $http docs, body is
The response body transformed with the transform functions.
With the 401 (Unauthorized) error you are getting back, it is quite possible there is no body being returned, hence why it is undefined.
If you want to log the error code, log the status parameter instead. It contains the HTTP Status Code, which should be uniform, unlike response bodies.

Categories