在处理来自 AngularJS 承诺的错误时,使用 '.catch(function(error)' 和 'function(errResponse)' 有什么区别?



我正在阅读AngularJS启动和运行。在第6章中,它提到了这样的承诺的处理错误:

$http.get('/api/server-config').then(function(configResponse) {
return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
// Display items here
}, function(error) {
// Common error handling
});

在其他地方,我看到正在使用.catch()(例如,这里的答案:将变量从工厂分配给控件不起作用,使用.catch()如下:

BaseService.fetch.stuffs
.then(function(data) {
self.stuffies = data;
console.log(self.stuffies);
}).catch(function(errorResponse) {
self.cerrorMessages = errorResponse.data;
});

我的问题是,上述薄荷和书中所示的方法有什么区别:

BaseService.fetch.stuffs
.then(function(data) {
self.stuffies = data;
console.log(self.stuffies);
}, function(error) {
self.cerrorMessages = errorResponse.data;
});

首选什么?

区别:

如果服务 api 中存在一些错误,则function(error) {}会捕获它。

但是,如果你的成功方法function(data){}抛出一些错误,那么只有.catch()才能抓住它。

例:

promise().then(function (data) {
throw new Error('execption from success');
}).catch(function (err) {
// execption from success caught!!
});
promise().then(function (data) {
throw new Error('execption from success');
}, function (error) {
// execption from success : NOT caught
});

阅读更多

首选的:

promise().then(function (data) {
// handle data
}, function (error) {
// handle error from api
}).catch(function (err) {
// handle error from response.
});

根据 AngularJS 1.2 文档

catch(errorCallback)promise.then(null, errorCallback)的简写

这意味着您可以互换使用 2 种语法。

catch语法更好,因为它将错误处理分离到自己的和单个通道,远离控制流,它被认为是良好的做法,由 bluebird 和其他人推广.js而使用错误处理程序函数作为 then 函数的第二个参数可以被视为反模式。

你可以找到一些关于它们的非常好的读物:

http://www.datchley.name/promise-patterns-anti-patterns/

http://taoofcode.net/promise-anti-patterns/

https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns

两者之间的差异可以通过一个例子来说明。至于你发布的第一段代码:

$http.get('/api/server-config').then(function(configResponse) {
// create another promising chain here
$http.get("/something-else").then(function(response) {
// Do something
}); 
return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
// Display items here
}, function(error) {
// Common error handling
});

如果我不只是返回 promise,而是在第一个 promise 解析器中调用另一个异步函数,则来自该函数的错误将永远不会到达最后一个错误处理程序,如果我忘记单独处理来自该新函数的错误,它将被吞噬。

但是,可以使用捕获来解决此问题:

$http.get('/api/server-config').then(function(configResponse) {
// create another promising chain here
$http.get("/something-else").then(function(response) {
// Do something
}); 
return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
// Display items here
}).catch(function(error) {
// error from nested function something else, can also be handled here 
// within a single error handling channel
});