处理角度承诺中的错误

时间:2016-01-14 22:52:08

标签: javascript angularjs promise

我仍在学习角度的承诺,并且在我做两次“GET”请求的地方有这些代码。我想在调用另一个之前运行一个get请求。这工作正常,但我如何处理错误?如果我的第一个GET请求出错,如何找出该错误是什么并阻止我的代码调用第二个GET请求?我的代码示例最有帮助。

    public static void AddRow(this ListView lvw, int image_index,
        string item_title, params string[] subitem_titles)
    {
        // Make the item.
        ListViewItem new_item = lvw.Items.Add(item_title, 1);

        // Set the item's image index.
        new_item.ImageIndex = image_index;
        // Make the sub-items.
        for (int i = subitem_titles.GetLowerBound(0);
                 i <= subitem_titles.GetUpperBound(0);
                 i++)
        {
            new_item.SubItems.Add(subitem_titles[i]);
        }
    }

2 个答案:

答案 0 :(得分:1)

我会做一些与Lucas略有不同的事情,我更喜欢链接一个catch块(基本上它会像我们使用的同步try...catch块一样),而不是添加一个错误回调函数,所以代码就像:

return $http.get(url1)
  .then(function(result){
    resultsObject.url1 = result;
    return $http.get(url2);
  }).then(function(result){
    resultsObject.url2 = result;
    return resultsObject;
  }).catch(function(error){
    // handle error.
  });
PS:你的大部分代码都很好,但我不确定为什么你有callback(resultsObject);,当你使用promises时,回调是多余的,你可以只返回promise链$http.get...

答案 1 :(得分:0)

您可以在第一个回调处理中传递第二个参数。如果请求中出现错误,则会触发,然后您可以随意处理:

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

或者在你的编码中:

$http.get('/someUrl').then(successCallback, errorCallback);

更多信息here

您的代码如下:

$http.get("http://magainteractive.com/prototypes/cisco-ima-dashboard/cms/web/api/login/login/?username="+user+"&password="+password+"")
    .then(function(contentResponse){
        resultsObject.content = contentResponse; 
        return $http.get("http://magainteractive.com/prototypes/cisco-ima-dashboard/cms/web/api/data/list/"); 
    }, function(error){ 
             //HANDLE ERROR HERE
       })
    .then(function(dataResponse){
        resultsObject.reports = dataResponse;
        resultsObject.success = 1;
        console.log(resultsObject);

        callback(resultsObject);
        apiServices.useData(resultsObject);
    }); 
相关问题