1

I am using angularJs factory its making call and working as expected but in terms of exception i have question what if we have exception after making call and it fails so in this case when i execute prcDeleteFactory.deletePrcInventory i want to check first if there is any error display error and stay on same page.

How can i resolve this problem using below code ?

ctrl.js

 function deleteInventory(inventory,controlId) {
      prcDeleteFactory.deletePrcInventory(inventory,controlId).then(function(){
        $scope.confirmationWin.close();
        $state.go('app.search');
      });
    }

factory.js

angular.module('App').factory('prcDeleteFactory',function($http){
  'use strict';
  return {
    deletePrcInventory: function(inventoryToDelete,key){
      return $http.get('app/delete/deleteInventory?inventoryToDelete=' + inventoryToDelete + '&key=' + key);
    }
  };
});

3 Answers 3

2

You need to "catch" error. If it happens promised returned by $http service gets rejected so you can handle it with catch (or error callback in then):

function deleteInventory(inventory,controlId) {
  prcDeleteFactory.deletePrcInventory(inventory, controlId).then(function() {
    $scope.confirmationWin.close();
    $state.go('app.search');
  })
  .catch(function(error) {
    $scope.error = 'Delete failed.';
  });
}
Sign up to request clarification or add additional context in comments.

6 Comments

How about if we have error message from server that we need to display in case of failure ?
There is also the option to have a second function parameter inside .then() to handle situations where your server-side code runs and returns an error.
@hussain You could set some error message on the scope.
Maybe @hussain is unaware that the standard form of .then() is .then(function successCallback(result){}, function errorCallback(error){}); You might consider adding that to your answer for completeness' sake.
@Lex I briefly mentioned it too, but anyway I wouldn't recommend error callback simply because it won't catch errors if they happen in the sibling success handler.
|
0

What about using the then / catch form :

 $http.get(/**/).then(function(response) {
    // do something with response
 }).catch(function(err) {
    // do something with error err
 })

Comments

0

The second parameter for .then()is the function that executes on error. Change your controller code to:

function deleteInventory(inventory,controlId) {
    prcDeleteFactory.deletePrcInventory(inventory,controlId).then(function(){
        $scope.confirmationWin.close();
        $state.go('app.search');
    }, function(error){
        //Some error occurred here
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.