Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling in AngularJS http get then construct

How can I handle an HTTP error, e.g. 500, when using the AngularJS "http get then" construct (promises)?

$http.get(url).then(     function(response) {         console.log('get',response)     } ) 

Problem is, for any non 200 HTTP response, the inner function is not called.

like image 528
Federico Elles Avatar asked Jun 13 '13 05:06

Federico Elles


People also ask

What is the correct syntax for making a get call and handling the error?

get(url) . then(function (response) { console. log('get',response) }) . catch(function (data) { // Handle error here });

Which object does the HTTP GET () function return?

response : interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.

How does Angular handle HTTP errors?

When the error occurs in the HTTP Request it is intercepted and invokes the catchError . Inside the catchError you can handle the error and then use throwError to throw it to the service. We then register the Interceptor in the Providers array of the root module using the injection token HTTP_INTERCEPTORS .

What is HTTP get in AngularJS?

get Method. In angularjs $http service is used to send or get data from remote http servers using browsers XMLHttpRequest object. In angularjs $http service is having many shortcut methods available like $http.


2 Answers

You need to add an additional parameter:

$http.get(url).then(     function(response) {         console.log('get',response)     },     function(data) {         // Handle error here     }) 
like image 192
laurent Avatar answered Sep 21 '22 16:09

laurent


You can make this bit more cleaner by using:

$http.get(url)     .then(function (response) {         console.log('get',response)     })     .catch(function (data) {         // Handle error here     }); 

Similar to @this.lau_ answer, different approach.

like image 33
Ravish Avatar answered Sep 21 '22 16:09

Ravish