Showing posts with label i18n messages from exception. Show all posts
Showing posts with label i18n messages from exception. Show all posts

Saturday, February 15, 2014

Accessing i18n Messages from exception (validation errors) in Grails in a Service

To access your message, inject the MessageSource into your service:
def messageSource  

And to get the error messages from exception based on your i18n properties file, use the following code block in your service:
 
def messageSource;

def printAllMessage(Exception ex) {
    ex.errors.allErrors.eachWithIndex { ObjectError objectError, Integer index ->
        println "Error #${index}: " + messageSource.getMessage(objectError, Locale.default);
    }
}


Will output something like this based on you i18n messages.properties file:

Error #0: Property [accountId] cannot be null
Error #1: Property [displayName] cannot be null
Error #2: Property [emailAddress] with value [pritom@bitmascot.com] must be unique

If your i18n file contains something like:

default.null.message=Property [{0}] cannot be null
default.not.unique.message=Property [{0}] with value [{2}] must be unique