javascript - 连接 RESTful API 时如何正确处理无法连接错误

标签 javascript rest mvvm promise canjs

我已成功加载数据并保存数据。但无法理解所需的错误处理方案。 当一切顺利时,我收到与发送的对象相同的对象,但带有额外的属性 _ saving (false)。

当出现问题时,例如尝试存储字符串而不是数字,我会得到:

  1. 错误的请求(控制台上出现错误,不希望出现这种情况)
  2. 响应对象(可能有助于显示错误)
  3. “未捕获( promise )”错误

示例:

代码:
this.save()
    .then(function(result) {
    console.log('ok1', result);
}).catch(function() {
    console.log('errorHandler1');
});
  • 好的:
    • https://www.dropbox.com/s/ogoc1opcmh6w23q/Screenshot%202016-09-24%2010.35.08.png?dl=1
  • 错误:
    • https://www.dropbox.com/s/hufs2b68t8bqfhl/Screenshot%202016-09-24%2010.36.02.png?dl=1

我一直在尝试使用 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/

相关文章:

ruby-on-rails - 使用 Backbone.js 加载模型关系

java - 无法在 spring rest 模板客户端中找到请求目标的有效认证路径

c# - 无法序列化和反序列化UserControl

visual-studio-2010 - 在 View 和 View 模型之间跳转

android - 在回收器 View 的适配器内的单项 View 中使用 ViewModel 方法好吗?

javascript - 在 contenteditable div 中触发所有 keydown/up 事件

javascript - 更改从脚本中获取的特定单词的颜色

javascript - 如何在 Next.js 中访问客户端窗口方法

rest - 如果客户端没有指定大集合的范围,REST 服务应该返回什么

javascript - 检查innerHTML是否为空