Meteor.Error没有显示任何内容

 章小胭 发布于 2023-02-10 11:46

我正在验证流星应用程序中的某些表单输入,并尝试使用Meteor.Error在字段验证失败时将一些信息返回给用户(如在显微镜中那样).但是,浏览器上没有显示任何内容(确实抛出)然而,进入控制台的错误).

  if(!firstN)                                                                                           |e
    {                                                                                                     |      
console.log("No first name given"); | } |
if(!lastN) |
{ |
console.log("No last name given"); |
} |
if(!message) | console.log("No mesage text given"); |
throw new Meteor.Error(422, 'Please provide a message'); |
1 个回答
  • 你必须用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.Errors并将它们返回给客户端.

    2023-02-10 11:48 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有