我使用throw new Meteor.Error
从服务器方法抛出错误。
客户端似乎没有提取它,回调的error
参数始终是undefined
,但在终端中它throws
错误并重新启动Meteor。
W20170413-17:27:28.900(1)? (STDERR) /home/xeconcepts/.meteor/packages/meteor-tool/.1.4.2-1-beta.1.si3hb0++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:280 W20170413-17:27:28.900(1)? (STDERR) throw(ex); W20170413-17:27:28.900(1)? (STDERR) ^ W20170413-17:27:29.175(1)? (STDERR) Error: carte existe [204] W20170413-17:27:29.175(1)? (STDERR) at imports/api/users/methods.js:211:47
和条纹methods
或
const Stripe = require('stripe');
const stripe = Stripe("sk_test_pO*******MUDXjlF8v");
仅适用于
if(Meteor.isServer)
如何从服务器端抛出错误并从客户端捕获它?
方法代码:
export const addCCStudent = new ValidatedMethod({
name: 'addCCStudent',
validate: new SimpleSchema({
id: {
type: String
},
number: {
type: String
},
dateMM: {
type: String
},
dateYYYY: {
type: String
},
cvc: {
type: String
}
}).validator(),
run(p) {
try {
if (Meteor.isServer) {
const Fiber = require('fibers');
const Stripe = require('stripe');
const stripe = Stripe("*************");
stripe.tokens.create({
card: {
"number": p.number,
"exp_month": p.dateMM,
"exp_year": p.dateYYYY,
"cvc": p.cvc
}
}, function(err, token) {
console.log("tokenserr", err);
console.log("token", token);
if (!err) {
Fiber(function() {
// console.log("p", p)
var user = Meteor.users.findOne({
_id: p.id
});
//console.log("addCCStudentuser", user);
if (user) {
var cCArray = user.profile.UserCards;
if (cCArray) {
var exist = false;
for (var i = 0; i < cCArray.length; i++) {
if ((cCArray[i].number == p.number) && (cCArray[i].dateMM == p.dateMM) && (cCArray[i].dateYYYY == p.dateYYYY)) {
exist = true
}
}
if (exist) {
throw new Meteor.Error(204, "carte existe");
} else {
Meteor.users.update({
_id: p.id,
}, {
$push: {
'profile.UserCards': { number: p.number, dateMM: p.dateMM, dateYYYY: p.dateYYYY }
}
});
}
}
}
}).run();
} else {
// console.log("errerrerrerr", err.raw.message);
throw new Meteor.Error(204, err.raw.message);
}
});
}
} catch (error) {
console.log("error", error)
throw new Meteor.Error(203, error.reason);
}
},
});
答案 0 :(得分:0)
理想情况下,Meteor应该捕获直接在方法中抛出的任何错误,但在您的情况下,由于大多数错误都包含在Fiber
函数调用中,这可能会加剧。
因此,您可能会在服务器端抛出错误,但它永远不会冒泡到方法的调用者(在客户端,并期望来自ValidatedMethod
的响应)。
尝试返回Fiber
函数的结果。查看fibers
包的文档中的示例,try-catch块需要围绕Fibers函数调用,而不是围绕ValidatedMethod的整个内容。
此外,您还可以尝试在所有错误陈述之前添加return
。 e.g。
return throw new Meteor.Error(204, "carte existe")
注意:如果您共享尝试访问此错误的客户端代码,也会很好。
答案 1 :(得分:0)
请试试这个。 在抛出错误的光纤内部,将其替换为抛出错误的函数
if (exist) {
ErrorFunction()
}
光纤外部放置功能
ErrorFunction() {
throw new Meteor.Error(204, "carte existe");
}
查看客户端是否能够捕获相同内容。