ejo*_*aud 14 javascript error-handling promise angularjs
在我的angularjs应用程序中,我以这种方式为http错误定义了一个默认处理程序:
myapp.config([ '$httpProvider', function($httpProvider) {
$httpProvider.responseInterceptors.push('errorInterceptor')
}])
Run Code Online (Sandbox Code Playgroud)
哪个errorInterceptor
服务在当前页面顶部的警报字段中显示有关错误的一些详细信息.
现在,当我想以不同的方式处理特定错误时(比如在模态中触发查询,我想仅在此模式中显示警报,而不是在页面级别):
$http.get('/my/request').then(success, specificErrorHandling)
Run Code Online (Sandbox Code Playgroud)
Angular确实specificErrorHandling
会触发我的errorInterceptor
,所以我的错误会被报告两次.有没有办法避免这种情况?
更一般地说,是否有一种Angular方法只处理promise
链中尚未处理的错误,就像服务器应用程序的顶级错误处理程序不必处理捕获的异常一样?
编辑:根据Beetroot-Beetroot在评论中的要求,这是我的拦截器的代码:
@app.factory 'errorInterceptor', [ '$q', 'alertsHandler',
($q, alertsHandler) ->
success = (response) ->
response
failure = (response) ->
alertsHandler.raise(response)
(promise) ->
promise.then success, failure
]
Run Code Online (Sandbox Code Playgroud)
我们有类似的东西.
如果我们处理http错误,我们会在请求的请求上传递一个属性 errorHandled:true
$http({
method: 'GET',
url: '/my/url',
errorHandled:true
}).then(function(){ ... }, function(){ ... });
Run Code Online (Sandbox Code Playgroud)
然后在拦截中responseError: function(rejection){ ... }
我们可以看到是否通过查看设置了这个标志rejection.config.errorHandled
,如果没有 - 那么我们会弹出带有错误的toastr对话框.代码看起来像这样
function ( rejection ) {
if ( !rejection.config.errorHandled && rejection.data.message ){
toastr.error(rejection.data.message, 'Error');
}
return $q.reject(rejection);
}
Run Code Online (Sandbox Code Playgroud)
有人在没有添加处理程序的情况下编写"errorHandled:true"的可能性很小.有2个错误指标的可能性也很小,因为我们已经习惯了 - 但实际上有2个指标优于没有指标.
如果我们有承诺查询它是否有错误处理程序或不在then
链中,那将是很好的,但我们无法在任何地方找到它.
假设您知道哪些错误需要被抑制以及哪些错误需要被传播。另外,由于 Response 拦截器是一个返回 Promise 本身的函数
您可以捕获失败情况的响应,而不是将其传播到堆栈中,您可以返回诸如空响应之类的内容。
如果您查看拦截器的角度文档中的示例示例
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return function(promise) {
return promise.then(function(response) {
// do something on success
}, function(response) {
// do something on error
if (canRecover(response)) {
return responseOrNewPromise; // This can suppress the error.
}
return $q.reject(response); // This propogates it.
});
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4078 次 |
最近记录: |