angularjs - 在哪里处理 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
})
我宁愿将错误处理移到服务中,但不确定控制器将如何等待数据可以处理......
解决方案
我想出的最好办法是处理服务中的错误并创建额外的承诺以发送回控制器:
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
推荐阅读
- linux - 如何制作 usbmon 日志文件 (*.mon)?
- python-3.x - 如何使用 UUID PrimaryKeyRelatedField 创建嵌套的 DRF 序列化程序?
- ruby-on-rails - Rails 6如何装饰application.html.erb
- python - 如何通过pygments(使用pygount)分析源代码并获得SUM
- javascript - 使用javascript制作评分计算器
- r - 如何使用 dplyr 创建一个表格,显示 R 中大型 csv 文件中的最大值?
- javascript - 如何使用 Jquery 以编程方式过滤剑道网格?
- javascript - 我不知道如何使用 post 方法从 IGDB api 获取数据
- c++ - 从外部类继承的嵌套私有类的正确模式
- ssh - 无法通过 ssh 进入 QNX 6.5.0 VirtualBox 会话