t.animal
t.animal

Reputation: 3331

Grails bind data to non-domain-class with type checking

I'm looking for a simple way to check some types in my params. If they exist they should have a certain type, if not they should have a default value. If they exist and their type is wrong, an exception should be thrown.

It would be nice to have the values in a handy container afterwards. Therefore I've tried passing params to the container's constructor and bindData on a container object. Neither is successful:

class ContainerClass {
     Integer foo = 42;
}

class TestController {

    def index(){
         //doesn't throw, **even when params.foo = "2asdf3"**
         ContainerClass meh = new ContainerClass();
         bindData(meh, params);

         println meh.foo //prints 42 when params.foo = "2asdf3"

         // throws GroovyCastException: Cannot cast object '23' with class
         // 'java.lang.String' to to class 'java.lang.Integer',
         // **even when params.foo = "23"**
         ContainerClass meh2 = new ContainerClass(params);
         render "meh"
    }
}

I'm using grails 3 if this is of importance.

Upvotes: 0

Views: 290

Answers (1)

Manali Khanna
Manali Khanna

Reputation: 101

You might use Command Objects to bind parameters to certain Data Type. Reference : http://docs.grails.org/latest/guide/single.html?utm_content=bufferf77f5&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer#commandObjects

If you want to throw exceptions if certain data type does not match,that needs to be checked explicitly.

Upvotes: 1

Related Questions