Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ilmoralito/a335050ca006c18e7af7a2e600d4cbb3 to your computer and use it in GitHub Desktop.
Save ilmoralito/a335050ca006c18e7af7a2e600d4cbb3 to your computer and use it in GitHub Desktop.
Grails Service: Validation Errors and Rollback
Validation Errors and Rollback
A common use case is to rollback a transaction if there are validation errors. For example consider this service:
import grails.validation.ValidationException
class AuthorService {
void updateAge(id, int age) {
def author = Author.get(id)
author.age = age
if (!author.validate()) {
throw new ValidationException("Author is not valid", author.errors)
}
}
}
To re-render the same view that a transaction was rolled back in you can re-associate the errors with a refreshed instance before rendering:
import grails.validation.ValidationException
class AuthorController {
def authorService
def updateAge() {
try {
authorService.updateAge(params.id, params.int("age"))
}
catch (ValidationException e) {
def author = Author.read(params.id)
author.errors = e.errors
render view: "edit", model: [author:author]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment