Tuesday 29 April 2008

What happens when you throw exceptions from services


class LolController {
def sessionFactory
def lolService
def gimmehCheezburger = {
def kitteh = Lolcat.get(params.id)
try {
lolService.canHasCheezburger(kitteh)
assert sessionFactory.currentSession.contains(kitteh)
} catch (EpicFailException wtf) {
assert !sessionFactory.currentSession.contains(kitteh)
}
render(view: 'lolcat', model: [lolcat: kitteh])
}
}

Note that the domain object 'kitteh' becomes detached from the hibernate session if the service throws an exception. This would cause reads of the object's lazy-loaded associations in the view rendering phase to fail.

If this is really what you want to do (it looks unpleasantly like controlling program flow via exceptions) you can use kitteh.refresh() in the catch block to re-attach the object to the hibernate session.

No comments: