我已成功加载数据并保存数据。但无法理解所需的错误处理方案。
当一切顺利时,我收到与发送的对象相同的对象,但带有额外的属性 _ saving
(false)。
当出现问题时,例如尝试存储字符串而不是数字,我会得到:
- 错误的请求(控制台上出现错误,不希望出现这种情况)
- 响应对象(可能有助于显示错误)
- “未捕获( promise )”错误
示例:
代码:this.save()
.then(function(result) {
console.log('ok1', result);
}).catch(function() {
console.log('errorHandler1');
});
- 好的:
- 错误:
我一直在尝试使用 catch on Promise,遵循以下准则: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch 但一点运气都没有。
这应该可以工作,只需将 p1.then
更改为 thisObjectThatIWantToSave.save.then
但事实并非如此。
p1.then(function(value) {
console.log(value); // "Success!"
throw 'oh, no!';
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
同样,当数据正确时它仍然存储信息,我看到的问题是我没有工具来决定数据何时正确存储或不正确存储,并避免触发可以正确处理的错误。
我正在使用
- canjs v3.0.0-pre.11
- feather提供的restful API
最佳答案
关于错误处理...
Bad request (error on the console, don't want that)
无法阻止控制台上的错误。这是 chrome 所做的事情。
The response object (might be usefull to show an error)
您可以在 can-stache 中阅读拒绝的原因
,例如 {{promise.reason}}
。
"Uncaught (in promise)" error
我不确定为什么会抛出这个问题,因为你的catch
正在被击中。如果将其更改为:
this.save()
.then(function(result) {
console.log('ok1', result);
},function() {
console.log('errorHandler1');
});
你有同样的行为吗?
关于javascript - 连接 RESTful API 时如何正确处理无法连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39677050/