首页 > 解决方案 > 在哪里处理 AngualrJS 后端错误

问题描述

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

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

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

myController.js

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

我的服务.js

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

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

我在 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
  })

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

标签: angularjserror-handlingpromiseangular-promise

解决方案


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

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


推荐阅读