如果方法中出现任何错误,我会在更新 mongoDb 中的文档时尝试抛出用户定义的错误。我正在调用方法并 try catch 错误,但我没有收到错误。仅在服务器控制台中打印错误。我怎样才能捕获客户端的错误?
我的代码示例如下所示:
//Method
methodName: (userData) ->
if(Meteor.isServer and this.userId)
User.update {_id:this.userId},{$set:{username:userData.username, "profile.name": userData.name ,"emails.$.address": userData.email}}, (error) ->
if error and error.code == 11000
throw new Meteor.Error 403, 'Email already in used'
//client Side
$meteor.call('methodName',result).then ((success) ->
console.log success // is undefined in both case, when updates and in case of error
if success
console.log 'data updated'
), (err) ->
console.log err // not entered in this region
最佳答案
您的代码有大量错误。
Meteor.methods({
methodName: function(userData){
// you have to create the $set hash programatically first
var setHash = {
"$set": {
"username": userData.username,
"profile.name": userData.name,
// what's going on here with the dollar sign you originally had?
"emails.0.address": userData.email
}
};
if( Meteor.isServer && this.userId() ){
// It's Users, not User
return Users.update( { _id: this.userId() }, setHash, function(error, numberOfAffectedDocuments){
if(error && error.code == "11000"){
// Error names have to be a string
throw new Meteor.error("403", "Email already in use.");
} else {
return "Success! The number of affected documents is " + numberOfAffectedDocuments;
});
};
}
});
// in your original code you never sent your Meteor Method any arguments when calling it
Meteor.call('methodName', userDataObject, function(error, result){
if(error){
console.log("there was an error: ", error);
} else {
console.log("method call was a success: ", result);
};
});
引用文献:
http://docs.mongodb.org/manual/reference/operator/update/set/#set-elements-in-arrays
关于javascript - meteor .js : Error not caught on client in method call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31018294/