I have a need to have a method to return Id in case of success and list of errors in case of fail.
ex code snippet:
def save = {
def errors = []
if(Employee.save(flush:true)){
return Employee.id
}else{
errors.add("Can't be saved")
return errors.
}
}
In Service class
ICalling
Employee.save() – .. so how to check if it is error or id that save method returns
Any suggestions around would be appreciated.
Don’t do this – even if you can make it somewhat more usable with Groovy, it’s a bad idea. In this case though, there are a few simple solutions. If you’re just passing the Employee instance and saving it in the service method, you don’t need to return anything:
This is because if it’s successful, the id will be set on the instance you passed in, and if not there will be one or more validation errors in the
errorsproperty (there’s no need for you to return a generic error message when there are actually useful error messages available).For example this would be the code you’d have in a controller calling the service:
If you want to pass in the data to create and save the new instance and return an Employee (this is the approach I usually take), it’s similar:
In this second case it’s important to separate the
savecall and thereturn, since if there is a validation errorsavereturnsnulland you want to always return a non-null instance. So do not do this:If you separate them you can check the errors and/or the id.
Also, make sure that you do not use closures in services like you have in your code (
def save = { ...). Only methods will be transactional since the Spring transaction handling doesn’t know about Groovy closures – they’re just fields that Groovy calls as if they were methods, but they’re not.