我正在验证流星应用程序中的某些表单输入,并尝试使用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
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么我没有在页面上显示任何内容.我以为可能是因为我没有安装错误的陨石包,但这样做并没有任何改变.
有任何想法吗?如果重要的话,我正在使用bootstrap-3.
钽
彼得.
你必须用try/catch块来实际捕获错误.在catch块中,您可以向用户显示消息.否则,错误将被记录到控制台并且JavaScript执行将停止(程序崩溃并且显示一个错误窗口,说" 未引发未捕获的异常"?).例如,您可以执行以下操作:
try {
validateInput();
} catch( e ) {
Session.set( "errorMessage", e.message );
}
Run Code Online (Sandbox Code Playgroud)
在您的模板助手中:
Template.myForm.errorMessage = function() {
return Session.get( "errorMessage" );
};
Run Code Online (Sandbox Code Playgroud)
在您的模板中:
<template name="myForm">
<form>
<p class="error">{{errorMessage}}</p>
<!-- more form stuff -->
</form>
</template>
Run Code Online (Sandbox Code Playgroud)
更新:
还有另一种方法可以使用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)
});
}
Run Code Online (Sandbox Code Playgroud)
如果你查看显微镜代码,你会发现它们只Meteor.Error在方法中使用.这实际上是主要目的Meteor.Error- Meteor知道如何将这种错误发送给客户端.如果您在客户端上抛出错误,则可以使用内置的JavaScript Error:
throw new Error( "message" );
Run Code Online (Sandbox Code Playgroud)
在内部,在服务器上,Meteor使用一个try/catch块来捕获Meteor.Errors并将它们返回给客户端.
| 归档时间: |
|
| 查看次数: |
2215 次 |
| 最近记录: |