15

Does anybody know how I could get the fieldError to print out in the example below.

for each item with an error, I would like to print custom error messages that I have defined in the messages.properties file

at the moment all this does is print the default error codes

item.errors?.allErrors?.each{ 
  println it.toString() 
}

I have seen other examples where you can lookup an error code for a field e.g.

it.getFieldError('title').code

but I would like to convert the default message into my new error message and print that.

uladzimir
  • 5,639
  • 6
  • 31
  • 50
mh377
  • 1,656
  • 5
  • 22
  • 41

2 Answers2

21

You need access to the messageSource bean, e.g. with

def messageSource

in your controller or service. Then you can access the messages with

def locale = Locale.getDefault()
for (fieldErrors in bean.errors) {
   for (error in fieldErrors.allErrors) {
      String message = messageSource.getMessage(error, locale)
   }
}
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • 1
    put def messageSource (in controller or service) Thanks this worked. item.errors?.allErrors?.each{ println messageSource.getMessage(it, null) }; I also found a good link which explains this better http://johnrellis.blogspot.com/2010/02/retrieve-grails-domain-errors-from.html – mh377 Jul 16 '10 at 22:59
  • 1
    Burt, it doesn't seem like this become any more straightforward since 2010. Is there a reason that the individual error objects don't have a `message` field that returns the specific message rather than having to import a bean and call a static method? – Charles Wood Mar 31 '14 at 16:52
1

A somewhat simplier solution with a better performance would be;

MessageSource messageSource //Inject the messageSource class

e.errors.allErrors.each {
  String message = messageSource.getMessage(it, Locale.default)
}

OR

If you want to deal only with field errors:

e.errors.fieldErrors.each {
   String message = messageSource.getMessage("modified.invalid.validator.message", [it.field, 'message'] as Object[], Locale.default))
}

Where modified.invalid.validator.message is the local string in your messages.properties. In this particular example, this message reads something like...

modified.invalid.validator.message=Property [{0}] of [{1}] does not pass validation
Pila
  • 5,460
  • 1
  • 19
  • 30