Michal_Szulc
Michal_Szulc

Reputation: 4177

Grails NumberFormatException or GroovyCastException with fields, that cause it

I'm throwing exceptions in services (especially these validation ones) and try-catch them in controllers. I'm getting data to

in firmController:

try{
    def data = request.JSON
    firmService.createAndSave(data)
}
catch(ValidationException exception){
}

in firmService:

def createAndSave(data){
    firm.year = data.year as BigDecimal
    firm.price = data.price as Float
    firm.employees = data.employees as Integer
    firm.name = data.name
    if(!firm.validate()){
        throw new ValidationException(null, firm.errors)
    }
    firm.save(flush:true)
    firm
}

but if I send JSON with invalid data: {year:"asd", price: "fgh", employees: "3", name: "zxc"} I got an NumberFormatException. I know, I can catch NumberFormatException (or some kind of my own exception) in controller but how can I get a fields/properties for which it were thrown (and still throw it as an exception)?

Upvotes: 0

Views: 150

Answers (1)

Sandeep Poonia
Sandeep Poonia

Reputation: 2188

With the current approach that you are using to initialize your domain object you can't. The NFE is being thrown when grails tries to cast String value asd as BigDecimal (data.year as BigDecimal) and it has nothing to do with ValidationException.

JSONObject class implements Map and in grails all Domains have a constructor that accepts a Map and can initialize the object using map properties. So instead of binding each property manually you can directly instantiate the object using new Firm(data) in firmService. In this way you will get a binding exception when grails will try to bind a non decimal value to a BigDecimal type field.

Upvotes: 1

Related Questions