elethan
elethan

Reputation: 16993

catch() on angularjs $http.get() call doesn't suppress error

I have the following code (simplified and running in codepen for the sake of example):

var app = angular.module("httptest", []);

app.controller("getjson", ["$scope", "$http", function($scope, $http) {
  $http.get("https://codepen.io/anon/pen/LVEwdw.js").
  then((response) => {
    console.log(response.data)
    console.log('in then')
    throw 'the error'
  }).catch((e) => {
    console.log('in the catch')
    console.log(e);
  });
}]);

My expectation here is that, if the catch() block is entered, the error will not show up in the console, except where logged explicitly (i.e., it will not show up in red). However, this is not the case, red error message prints to the console, and then the catch() block is entered. I tried to set up an equivalent example here that does not use AngularJS's $http, and it behaves the way I expect:

var promise1 = new Promise(function(resolve, reject) {
  resolve();
});

promise1.then((result) => {
  console.log('about to throw error')
  throw 'hey'
 }).catch(function(error) {
  console.log(error);
});

In this example, no red error makes it through.

What is going on here, and is it possible to suppress the handled error in the $http case?

Upvotes: 0

Views: 727

Answers (2)

georgeawg
georgeawg

Reputation: 48968

That behavior was fixed with the release of AngularJS 1.6:

From GitHub commits:

fix($q): treat thrown errors as regular rejections

Previously, errors thrown in a promise's onFulfilled or onRejected handlers were treated in a slightly different manner than regular rejections: They were passed to the $exceptionHandler() (in addition to being converted to rejections).

AngularJS GitHub Commit e12eea

See also AngularJS Developer Guide - Migrating to V1.6 - $q

Upvotes: 1

bigless
bigless

Reputation: 3091

You can find explanation at line 8416 in your linked angularjs module. They simply console.error in catch statement. You can override this behaviour, f.e. by empty handler:

angular.module('exceptionOverride', []).factory('$exceptionHandler', () => (exception, cause) });

var app = angular.module("httptest", ['exceptionOverride']);

....

Upvotes: 1

Related Questions