I'm reading a book called, "Pro Angular JS". However, I have a question about how to catch a status of error.
What I coded is :
$http.get(dataUrl) .success(function (data){ $scope.data.products = data; }) .error(function (error){ $scope.data.error=error; console.log($scope.data.error.status); // Undefined! // (This is the spot that I don't get it.) });
If I code "console.log($scope.data.error.status);" , why does the argument of console.log is undefined?
In the book, there are sentence, "The object passed to the error function defines status and message properties."
So I did $scope.data.error.status
Why is it wrong?
One traditional way of handling errors in Angular is to provide an ErrorHandler class. This class can be extended to create your own global error handler. This is also a useful way to handle all errors that occur, but is mostly useful for tracking error logs.
The basic way to handle errors in Angular is to use Angular's HttpClient service along with RxJS operators throwError and catchError. The HTTP request is made, and it returns the data with a response if anything wrong happens then it returns an error object with an error status code.
A response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.
The default Error handling in Angular is handled by Errorhandler class, which is part of the @angular/core module. This is global error handler class which catches all exception occurring in the App. This class has a method handleError(error) .
The $http
legacy promise methods success
and error
have been deprecated. Use the standard then
method instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http
Now the right way to use is:
// Simple GET request example: $http({ method: 'GET', url: '/someUrl' }).then(function successCallback(response) { // this callback will be called asynchronously // when the response is available }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. });
The response object has these properties:
A response status code between 200 and 299 is considered a success status and will result in the success callback being called.
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