【问题标题】:Where to handle AngualrJS backend errors在哪里处理 AngularJS 后端错误
【发布时间】:2018-11-20 22:57:43
【问题描述】:

在审查 AngularJS 应用程序时,我很震惊,我真的不知道如何在控制器级别处理来自数据库的错误。

我们有一个三层结构controller -> service -> rest

Rest 服务处理对后端数据库的调用并向中间层服务返回一个承诺,中间层服务在大多数情况下将其交给控制器

myController.js

myService.getdata().then(function (result) {
  $scope.data = result
})

myService.js

this,getdata = function () {
  return RestService.get('url/to/my/data')
}

RestService 愉快地从后端 API(通过 hapi/Boom)返回错误,这些错误可以被 myServicemyController 捕获。我正在努力的是在服务而不是控制器中构建错误处理程序。

我在Controller中的最佳尝试如下:

  .then(function (result) {
    $scope.data = result
    // do something with the data
  })
  .catch(function (error) {
    console.error('data could not be loaded')
  })
  .finally(function () {
    // tidy up here
  })

我宁愿将错误处理移到服务中,但不确定控制器将如何等待数据可用于处理...

【问题讨论】:

  • 好吧,除了$httpProvider 中的custom interceptor,您可以尝试只传递两个回调:this.getdata = function (success, error) { return RestService.get('url/to/my/data').then(success, error)
  • @AlekseySolovey $http.success 和 $http.error 已在 AngularJS 1.6 中删除,如果这就是您所说的
  • 我说的是把你自己的函数作为参数传递。它们将作为可以在服务中执行的回调

标签: angularjs error-handling promise angular-promise


【解决方案1】:

我想出的最好办法是处理服务中的错误并创建额外的承诺以发送回控制器:

this.getdata = function () {
  //returns the $q.resolve or $q.reject promises with customized data
  return RestService.get('url/to/my/data').then(function(response) {
    // format the data differently from response, etc.
    var _data = customProcessing(response.data);

    // you can even decide, on your own if there is an error
    // if(someCondition) { return $q.reject("Custom error"); }

    return $q.resolve(_data);
  }).catch(function(error) {
    // throw up a modal, etc.
    var _error = customProcessing(error);
    return $q.reject(_error);
  }).finally(function() {
    //to do
  });
}

此示例允许您的服务层充当中间件。它获取数据,然后在执行自己的功能后将控制权返回给控制器:

myService.getdata().then(function (data) {
  $scope.data = data;
}).catch(function(error) {
  //optional catch clause. I use it to stop loading spinners
  //or to show error message below a form
});

这是一个工作示例:https://plnkr.co/edit/35zx59yHUJ1Zrf5LWp3W?p=preview

【讨论】:

  • 我也打算这样做。但是,如果我遵循上述模式,则会收到 TypeError Cannot read property 'then' of undefined,这表明该服务没有返回 Promise。无论我是否在后端强制出错,都会发生错误。
  • 您应该使用最简单的示例创建一个 plunker(JS 沙箱,plnkr.co/edit),以便我们帮助您调试
猜你喜欢
  • 2012-09-09
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 2019-12-11
相关资源
最近更新 更多