2013-12-18 68 views
0

我已经用AngularJS构建了一个简单的应用程序。这个应用程序的一部分是调用REST服务。为此,我正在使用猫鼬。一切都很好,但我想更好地处理错误。示例代码可能是:AngularJS Mongoose错误处理

快递:

DBCollection.find({}, function (err, tuples) { 
      if (err) { 
       console.log('Error!'); 
      } 
      res.send(JSON.stringify(tuples)); 
     }); 

AngularJS:

DBService.query(function (res) { 
      $scope.data.lists = res; 
}); 

我面对的问题是如下。想象一下,我在mongodb服务器端出现错误。我有一个错误,所以我将它记录在控制台中,然后呢?在angularjs /前端方面会发生什么?如果我将错误作为http响应发送,那么我认为angular会将其解释为查询的响应,但意外的内容会产生异常?如何处理?

回答

0

角度就像圣诞老人,它知道什么时候回应不好或好。有两种解决方案,其中一种解决方案是在每个请求上创建一个错误处理程序。另一种方法是使用$httpProvider.interceptors在错误成为单个请求级别上的问题之前全局处理错误。

选项1个

DBService.query(function (res) { 
    scope.data.lists = res; 
},function(errorResult){ 
    console.log(errorResult); // <- take a peek in here, find something useful 
}); 

选项2

$httpProvider.interceptors.push(['$q',function($q) { 
    return { 
     'responseError': function(rejection) { 
      console.log(rejection); // <- take a peek in here, find something useful 
      return $q.reject(rejection); 
     } 
    } 
}]); 
+1

我忘了,$资源下,它是$ http和承诺有两种方法成功和错误。此外,我并不熟悉$ q,拦截器的情况更少...所以我会采用选项1.谢谢! – GuillaumeA