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
.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";
}
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');
}
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