I am trying to handle exception in angular js .I am able to handle in one scenario but on scenario it fail to handle why ?
Actually when anything is undefined it is catch my $exceptionHandler.But when file is not found it is not catch by $exceptionHandler why
Example plunker http://plnkr.co/edit/mm4Uix8XXVrkhexW15vR?p=preview
case 1
when I hit this
$http.get("default.json").then(successcallback, errorcallback);
on success alert(data.hhh.getname()); it is undefined which is catch by
$exceptionHandler and store in array .Here is the output
case 2 But when I change the name of file default.son to defaul.json it is not catch by $exceptionHandler why ? and it show 404 error on console.can we catch this error and print on console ? can we catch this error ..?
Actually I don't want to get this error
how to handle this error ?
See documentation for $exceptionHandler. Note the part:
Note, that code executed in event-listeners (even those registered using jqLite's on/bind methods) does not delegate exceptions to the $exceptionHandler (unless executed during a digest).
What this means is that $exceptionHandler
catches uncaught exception thrown from a digest cycle. However if you actually click on the line where the 404 is thrown, you should notice that it's thrown by XHR, outside of Angular's $apply, therefore $exceptionHandler
is not in a scope outside of it to catch it. On the other hand, your data.hhh.getname()
is in a $q success callback, which is wrapped in an $apply, so it was caught by $exeptionHandler
.
EDIT Actually the article I linked for digest cycle explains this better.
Keep in mind that you should always use the version of $apply() that accepts a function argument. This is because when you pass a function to $apply(), the function call is wrapped inside a try...catch block, and any exceptions that occur will be passed to the $exceptionHandler service.
It's more than just a digest cycle, it needs to be inside $apply's scope. Otherwise Angular won't have an opportunity to put try ... catch
block anywhere to catch exceptions and pass it to $exceptionHandler
.
EDIT Upon closer inspection, the 404 that you see in console is not even an exception. It's logged to console.error
by XHR, which is a native API. So what you see in console will have to stay and cannot be caught. However notice that you can always check $http
failures in its failure callback, so you can inject $exceptionHandler
(which I see you have configured on your own) and manually log with it. eg.
responseError: function(error){
$exceptionHandler(new Error(
error.config.method + ' ' +
error.config.url + ' ' +
error.status +' ' +
'(' + error.statusText + ')'
));
return $q.reject(error);
}
See Plunker