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.
get(url) . then(function (response) { console. log('get',response) }) . catch(function (data) { // Handle error here });
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.
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 .
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.
You need to add an additional parameter:
$http.get(url).then( function(response) { console.log('get',response) }, function(data) { // Handle error here })
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With