Forked from ddelponte/controllerAndServiceValidationHandling.groovy
Created
October 28, 2017 04:30
-
-
Save ilmoralito/a335050ca006c18e7af7a2e600d4cbb3 to your computer and use it in GitHub Desktop.
Grails Service: Validation Errors and Rollback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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