Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promises - catch is not working

Why is it that the following code doesn't catch the exception being thrown?

$http.get(null)        // <- this throws a fit
.catch(function (e) {
  console.log(e);      // <- this is not being triggered
});

Error: [$http:badreq] Http request configuration url must be a string or a $sce trusted object. Received: null https://errors.angularjs.org/1.7.2/$http/badreq?p0=null

like image 243
kylemart Avatar asked Dec 10 '22 05:12

kylemart


2 Answers

.catch() is not a replacement for normal try catch.

It is specifically for handling exceptional circumstances that occurred during the promise resolution process.

In this case, the exception (throwing a fit) is happening outside the promise resolution process.

Your supplying invalid input to the $http.get method causing an exception before an XHR even gets created, not something going wrong with the HTTP request or any subsequent processing.

Here is an equivalent of what is happening:

try {
  $http.get(throwAnException()) 
    // .catch isn't even being evaluated!
    .catch(function(e) { 
      console.error(e); // no chance of being called      
    });

} catch (e) {
  // I would be evaluated
  console.error(e);
}

function throwAnException() {
  throw "An error before we even start";
}
like image 57
Ken Colton Avatar answered Dec 28 '22 01:12

Ken Colton


You need to understand that this catch is waiting for a "rejection" from your get call.

In other words, your $http.get is triggering an error and never returning a promise...this way, you can't execute a catch straight from an error, get it?

If you have $http.get("xyz") it will then do its thing and reject, therefore, being caught by your catch.

What you are doing results in this

// step 1
$http.get(null)
    .catch()

// step 2
ERROR
    .catch() // will not even get here, but if it did, it wouldn't work either

While, if your get could work, but rejected, you would have:

// step 1
$http.get('someFailingURL')
    .catch()

// step 2
RejectedPromise
    .catch() // gonna work :)

If your url comes from a different source (and that's why you get a null value for it some times) you should probably validate it before trying and getting it, like so:

if (yourVariableURL !== null) {
    $http.get(yourVariableURL)
        .catch()
} else {
    console.log('Invalid url');
}
like image 20
Felipe N Moura Avatar answered Dec 28 '22 00:12

Felipe N Moura