meteorcollectionssimple-schema

Error handling in Meteor.js with SimpleSchema


I'm working a project developing by Meteor.js & now I'm working for a validation something like that

import SimpleSchema from 'simpl-schema';

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

Company.attachSchema(CompanySchema);

but in the console showing like below image

enter image description here

but when trying to keep the "Error" like this way

console.log(err.Error);

it's showing

undefined

here is insert functionalities

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

what's the issue actually.

Thanks


Solution

  • When your client-side Mongo insert fails it produces a native Error. If you log it's name, message and stack it shows the expected properties of an Error:

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

    Produces:

    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)
    

    The attribute err.error in contrast is part of the Meteor.Error, which is thrown if the insert fails inside a Meteor Method.

    This would be the case for example in such code:

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