javascript - Meteor.Error 抛出给客户端时是否会发生变化?

标签 javascript node.js meteor callback

我有这个:

Meteor.methods({
  'foo'() {
    try{
      ...//some http.get
    } catch (e) {
      console.log(e); //-> { [Error: ETIMEDOUT] code: 'ETIMEDOUT', connect: true } 
      if(e.code === 'ETIMEDOUT') { throw e; }
    }
  }
});

所以现在我在客户端:

Meteor.call('foo', function(error, result) {
  if(error){
    if(error.code === 'ETIMEDOUT') {
      //this block is never reached.. why?
    }
  }
}

但似乎错误代码与服务器上的不一样(似乎已更改为内部服务器错误)。为什么是这样?更重要的是,我怎样才能得到原来的(在本例中超时)错误?

最佳答案

来自 manual :

When you have an error that doesn’t need to be reported to the client, but is internal to the server, throw a regular JavaScript error object. This will be reported to the client as a totally opaque internal server error with no details.

这就是你所看到的。相反:

When the server was not able to complete the user’s desired action because of a known condition, you should throw a descriptive Meteor.Error object to the client. Meteor.Error takes three arguments: error, reason, and details.

所以你可以这样做:

if (e.code === 'ETIMEDOUT') {
  let userMessage = 'The remote call timed out.';
  let detail = `${userMessage}: ${JSON.stringify(e)}`;
  console.error(detail);
  throw new Meteor.Error('remote-call-timed-out', userMessage, detail);
}

第一个参数“错误”(我称之为“代码”)是您可以在客户端上进行编程以采取特定操作或国际化用户消息的参数。这就是我们在系统中所做的事情。 (如果未找到代码,我们将显示 userMessage)。详细信息将写入服务器日志并放入浏览器 console.log 中。

关于javascript - Meteor.Error 抛出给客户端时是否会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45009995/

相关文章:

JavaScript 和 Jquery : Uncaught TypeError: Cannot read property 'length' of undefined

javascript - 更新形状属性时的对象一致性

node.js - NodeJS API 如何查询和响应

javascript - HTML 元素添加到 Javascript for 循环中,然后在计数器递增时删除

javascript - 使用身份证号码隐藏下拉菜单

node.js - Telegram Bot - NodeJs - 任务在循环中

node.js - 用 nock 模拟一个开放的网络套接字

javascript - 铁路由器: Meteor JS

meteor - 如何使用Centos7在生产服务器中部署meteor应用程序

javascript - 尽管有 React 的 onClick 处理程序,history.back() 似乎并没有等待点击