我在流星应用程序中验证某些表单输入,并尝试使用Meteor.Error在字段验证失败时将一些信息返回给用户(如在显微镜中所做的那样)。但是,浏览器中没有显示任何内容(确实会向控制台抛出错误)。
if(!firstN) |e</label>
{ | <div class="col-sm-10">
console.log("No first name given"); | <input type="text" class="form-control" id="
throw new Meteor.Error(422, 'Please provide a First Name'); |lname" placeholder = "Required"/>
} | </div>
if(!lastN) | </div>
{ | <div class="form-group">
console.log("No last name given"); | <label class="col-sm-2 control-label">Email</l
throw new Meteor.Error(422, 'Please provide a Last Name'); |abel>
} | <div class="col-sm-10">
if(!emailAdd) | <input type="email" class="form-control" id=
{ |"email" placeholder = "Required"/>
console.log("No email address given"); | </div>
throw new Meteor.Error(422, 'Please provide an Email Address'); | </div>
} | <div class="form-group">
if(!message) | <label class="col-sm-2 control-label">Phone Nu
{ |mber</label>
console.log("No mesage text given"); | <div class="col-sm-10">
throw new Meteor.Error(422, 'Please provide a message'); | <input type="tel" class="form-control" id="p
}
我不确定为什么我没有在页面上显示任何内容。我以为可能是因为我没有安装错误的陨石包,但这样做并没有任何改变。
有什么想法吗?如果重要的话,我正在使用bootstrap-3。
TA
彼得。
答案 0 :(得分:5)
您必须使用try/catch
块实际捕获错误。在catch块中,您可以向用户显示消息。否则,错误将被记录到控制台并且JavaScript执行将停止(程序崩溃并且显示一个错误窗口,说“引发了未捕获异常”?)。例如,您可以执行以下操作:
try {
validateInput();
} catch( e ) {
Session.set( "errorMessage", e.message );
}
在你的模板助手中:
Template.myForm.errorMessage = function() {
return Session.get( "errorMessage" );
};
在你的模板中:
<template name="myForm">
<form>
<p class="error">{{errorMessage}}</p>
<!-- more form stuff -->
</form>
</template>
更新
还有另一种方法可以使用Meteor.Error
。如果从服务器上的方法中抛出错误,它会将错误对象返回到客户端到方法回调,并且您不需要使用try / catch块。例如:
Meteor.methods({
foo: function( bar ) {
if ( bar === "baz" ) {
return true;
} else if ( bar === "qux" ) {
return false;
} else {
throw new Meteor.Error( "bah humbug" );
}
}
});
if ( Meteor.isClient ) {
Meteor.call( "foo", function( error, result ) {
// We didn't provide a `bar` argument, so the method will throw an error.
// We can handle the error in this callback (no try/catch needed)
});
}
如果查看显微镜代码,您会发现它们只使用方法中的Meteor.Error
。这实际上是Meteor.Error
的主要目的 - Meteor知道如何将这种错误发送给客户端。如果您在客户端上抛出错误,则可以使用内置JavaScript Error
:
throw new Error( "message" );
在内部,在服务器上,Meteor使用try/catch
块来捕获Meteor.Error
并将它们返回给客户端。