omer bach
omer bach

Reputation: 2395

Catch http error in angular js

I'm not able to catch the http error in the error function call back when posting an http request.

Here is the client side:

$http.post('/updateBuildings', 
            $.param(
                {'element_id': element_id}
            )).success(function(data) {
                tmp.GetBuildings(data.new_building_id);         
            }).error(function(data) {
                console.log('response: ',data);
            });

    };

The server side is returning an http error deliberately : status code: 401, msg: "Sorry, access denied."

http error written by browser to console

The browser (google chrome) writes to the log by itself (see attachment) but I'm not able to catch the error in angular and present an alert for the user for example.

Any ideas?

Thanks

Upvotes: 0

Views: 489

Answers (1)

Michal Charemza
Michal Charemza

Reputation: 27012

I've had problems using success and error: they don't behave quite as I expect with respect to promises chaining and errors. While I'm not sure if that's what's going on here, I would suggest not using success and error, but use the standard promise then / catch functions.

$http.post('/updateBuildings', $.param({
  'element_id': element_id
})).then(function(response) {
  return tmp.GetBuildings(response.data.new_building_id);         
}).catch(function(error) {
  console.log('response: ', error.data);
});

Upvotes: 1

Related Questions