sylvainpolletvillard / ObjectModel

Strong Dynamically Typed Object Modeling for JavaScript
http://objectmodel.js.org
MIT License
467 stars 30 forks source link

I can't catch the exceptions #170

Closed M-Gonzalo closed 1 year ago

M-Gonzalo commented 1 year ago

Hi. I'm try-catching an ObjectModel instance but there is nothing inside the catch statement. I see the errors in console, and my program crashes, but I just don't see how I should handle it. In the docs I only see console.logs's, but that doesn't prevent me from crashing the app. Can somebody explain? Thank you!

sylvainpolletvillard commented 1 year ago

You need to configure an error collector: https://objectmodel.js.org/#doc-custom-collectors

Here is a simple "throw with custom message" error collector that can work on any model:

Model.prototype.errorCollector = function(errors){
    throw new Error(`ObjectModel global error collector caught these errors: ${errors.map(e => e.message)}`);
};

const Student = ObjectModel({
    name: String,
    course: [ "math","english","history" ],
    grade: Number
}).assert(student => student.grade >= 60,
          "should at least get 60 to validate semester")

new Student({ name: "Joanna", course: "sleep", grade: 0 });
M-Gonzalo commented 1 year ago

Oh, I see. I tried that but I was returning instead of throwing. I already implemented my own validations for the work I was doing but it's good to know how to make this work. Thanks!