2017-11-25 3 views
-2

私はrestful API facotiresエラー処理のさまざまな例を見てきましたが、これはちょっと混乱します。 1がベストプラクティスですAngularJS HTTPリクエストのエラー処理

angular.module('app').controller('userCtrl', function($scope, User) { 
    $scope.users = []; 
    $scope.error = ''; 

    User.getUsers().then(function(response) { 
     $scope.users = response.data; 
    }, function(response) { 
     $scope.error = 'Users not found'; 
    }) 
}); 

angular.module('app').factory('User', function($http) { 
    var service = {}; 

    service.getUsers = function() { 
     return $http.get('url-here').then(function(response) { 
      return response; 
     }); 
    } 

    return service; 
}); 

B

angular.module('app').controller('userCtrl', function($scope, User) { 
    $scope.users = []; 
    $scope.error = ''; 

    User.getUsers().then(function(response) { 
     if(response.status == 404) { 
      $scope.error = 'Users not found'; 
     } else { 
      $scope.users = response.data; 
     } 
    }); 
}); 

angular.module('app').factory('User', function($http) { 
    var service = {}; 

    service.getUsers = function() { 
     return $http.get('url-here', function(response) { 
      return response; 
     }, function(response) { 
      return response; 
     }); 
    } 

    return service; 
}); 

:ここでは、2つの例がありますか?同様に、ユーザーが見つからない場合は、 はユーザーがいないことを伝えたいのですが、内部サーバーのエラー(500)がある場合は、「何かが間違っている、後でやり直してください。

+1

をANを識別するのに十分なディテールを持つ特定の問題にそれを制限するために、質問を編集してください適切な答え。一度に複数の異なる質問をしないでください。 AとBはともにエロルートであり、オプションBは悪化しています。 – georgeawg

+0

申し訳ありません、私の質問を編集しました@georgeawg – Jis0

+0

この質問を削除し、修正するための例が1つしかない新しい質問を書きましょう。 – georgeawg

答えて

0

私は2つの理由から、オプションとなるだろう:

  • エラーが発生したことを明示的です。
  • これらのエラーは、表示されるページに応じてパーソナライズすることができます(ユーザーが属するページまたはコンポーネントに応じて異なるエラーを処理することがあります)。

その後、あなたはそうのようなエラーコードに基づいて、特定のメッセージを提供するためにswitchステートメントを使用することができます。

User.getUsers().then(function(response) { 

    $scope.users = response.data; 

}, function(response) { // error has occured 

    switch(response.status) { 

     case "404": 
      $scope.error = "Users not found."; 
      break; 

     case "403": 
      $scope.error = "You do not have permission to view these users."; 
      break; 

     case "500": 
      $scope.error = "We are having server issues. Please try again in 10 minutes."; 
      break; 
    } 
}); 
関連する問題