Meteor.call
当在服务器代码中,发生错误时,我无法在客户端的错误回调中获取错误Meteor.bindEnvironment
。以下是要复制的示例代码
在服务器中
Meteor.methods({
customMethod: function(arg1, arg2){
Stripe.customers.create({
email: "[email protected],
description: "blah blah",
source: token,
metadata: {
planId: planId,
quantity: n
},
plan: planId,
quantity: n
}, Meteor.bindEnvironment(function (err, customer) {
if(err){
console.log("error", err);
// TODO cannot catch this error on the client
throw new Meteor.Error(err.rawType, err.message)
}
}))
}
})
在客户端发生流星事件时,
Meteor.call('customMethod', arg1, arg2, function (err, resp) {
if(err){
Session.set('some-error', err)
}
if(resp){
// TODO cannot catch errors throwing from the server
// when inside Meteor.bindEnvironment
Session.set('some-success', true)
}
});
会话变量从不设置。任何帮助将是巨大的。谢谢!
的第二个参数Meteor.bindEnvironment
是一个错误处理程序,只要您在作为第一个参数提供的回调中抛出异常,就会调用该错误处理程序。因此,您可以执行以下操作将错误传递回客户端:
Meteor.bindEnvironment(function (err, customer) {
if (err) throw err
...
}, function (err) {
if (err) throw new Meteor.Error(err.message)
})
更新
抱歉,这有点草率。问题在于您的错误(以及可能的结果)来自异步回调,因此您的方法函数将完成执行,并在回调执行任何操作时隐式返回undefined
(将其作为传递给客户端null
)。
从历史上看,您会用future解决这个问题,但是现在我们有了更好的承诺:
Meteor.methods({
customMethod (arg1, arg2) {
return new Promise((resolve, reject) => {
Stripe.customers.create({
email: "[email protected],
...
}, Meteor.bindEnvironment(function (err, customer) {
if(err){
reject(err)
}
resolve(customer)
})).catch(e => { throw new Meteor.Error(e) })
}
})
流星方法足够聪明,可以等待承诺解决或拒绝并通过DDP返回结果(或错误)。您仍然需要捕获错误并正式将其抛出,但是您的方法调用将等待您这样做。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句