我正在验证流星应用程序中的某些表单输入,并尝试使用Meteor.Error在字段验证失败时将一些信息返回给用户(如在显微镜中那样).但是,浏览器上没有显示任何内容(确实抛出)然而,进入控制台的错误).
if(!firstN) |e { |console.log("No first name given"); | } |if(!lastN) |
你必须用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
s并将它们返回给客户端.