使用SimpleSchema处理Meteor.js中的错误

时间:2019-03-04 11:44:03

标签: meteor collections simple-schema

我正在工作一个由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);

但是在控制台中显示如下图

enter image description here

但是尝试以这种方式保留“错误”时

console.log(err.Error);

正在显示

undefined

这是插入功能

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

实际上是什么问题。

谢谢

1 个答案:

答案 0 :(得分:2)

当您的客户端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
})