【问题标题】:Error handling in Meteor.js with SimpleSchema使用 SimpleSchema 处理 Meteor.js 中的错误
【发布时间】:2019-07-25 17:24:44
【问题描述】:

我正在做一个由 Meteor.js 开发的项目,现在我正在做类似的验证

import SimpleSchema from 'simpl-schema';

const CompanySchema = new SimpleSchema({
    company_name: {
        type: String,
        min: 5,
        max: 50,
        label: "Company Name"
    }
});

Company.attachSchema(CompanySchema);

但在控制台中显示如下图

但是当试图以这种方式保持“错误”时

console.log(err.Error);

显示出来了

undefined

这里是插入功能

Company.insert(
    {
        company_name: inputs.companyName.value,
    },
    function(err) {
        if (err) {
            console.log(err);
        } else {
            console.log('Inserted successfully');
        }
    }
);

实际上是什么问题。

谢谢

【问题讨论】:

  • 能否将插入文档的方法的代码添加到集合中?
  • @Jankapunkt 更新了问题并在我的问题下方添加了功能
  • 我觉得应该是err.message。此外,您可以在插入之前验证对象,如 here 所示。

标签: meteor collections simple-schema


【解决方案1】:

当您的客户端 Mongo 插入失败时,它会生成 native Error。如果您记录它是namemessagestack,它会显示Error 的预期属性:

Company.insert(
    {
        company_name: inputs.companyName.value,
    },
    function(err) {
        if (err) {
            console.log(err.name);
            console.log(err.message);
            console.log(err.stack);
        }
    }
);

生产:

Error 
Company Name must be at least 5 characters in company insert
Error: Company Name must be at least 5 characters in company insert
    at getErrorObject (collection2.js:498)
    at doValidate (collection2.js:470)
    at Collection.Mongo.Collection.(:3000/anonymous function) [as insert] (http://localhost:3000/packages/aldeed_collection2.js?hash=9ed657993899f5a7b4df81355fd11d6b77396b85:286:14)
    at Blaze.TemplateInstance.helloOnCreated (main.js:10)
    at blaze.js?hash=51f4a3bdae106610ee48d8eff291f3628713d847:3398
    at Function.Template._withTemplateInstanceFunc (blaze.js?hash=51f4a3bdae106610ee48d8eff291f3628713d847:3769)
    at fireCallbacks (blaze.js?hash=51f4a3bdae106610ee48d8eff291f3628713d847:3394)
    at Blaze.View.<anonymous> (blaze.js?hash=51f4a3bdae106610ee48d8eff291f3628713d847:3474)
    at fireCallbacks (blaze.js?hash=51f4a3bdae106610ee48d8eff291f3628713d847:2014)
    at Object.Tracker.nonreactive (tracker.js:603)

相比之下,属性err.errorthe Meteor.Error 的一部分,如果在Meteor Method 内插入失败,则会抛出该属性。

例如在这样的代码中就是这种情况:

Meteor.call('someInserMethod', { company_name: 'abc' }, (err, res) => {
  console.log(err) // this error is a Meteor.Error
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2016-08-18
    • 2016-01-12
    • 2019-11-14
    • 2016-03-28
    • 1970-01-01
    相关资源
    最近更新 更多