我有这个:
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/