How can I get a single error message from a command object in grails?
all the examples I see are using similar to commandObject.errors.allErrors() but nothing if I only want the single error message to read into the controller and subsequently passed to the view.
An开发者_Go百科y ideas?
There is no heler to get as a single error message. Here is what I use:
For JSON:
def errors = user.errors.allErrors.collect{
['message': messageSource.getMessage(it, null) ,
'field': it.getField(),
'badValue': it.getRejectedValue()
]
}
render(status:400, contentType: "application/json"){
[message:'Failed to save', 'errors': errors]
}
For HTML(not ideal for most users error messages are to techincal):
flash.message = user.errors.allErrors.collect{
"Field:${it.getField()}| Error: ${messageSource.getMessage(it, null)}, value:${it.getRejectedValue()}"
}.join('\n')
I'm not sure what "single" error you want to retrieve (for a single field?), but just wanted to point out that commandObject.errors is of type org.springframework.validation.Errors
, so just have a look at the methods declared in this interface. There are methods to get the field errors, global errors etc. If you could clarify your question, we can perhaps provide a more detailed answer..
As you want to send single error message as response
have a look at spring Errors
interface here.
For all errors into one single error message check @Nix answer
AND
For a particular field, you can use on of following
Example: Consider field `status` having with invalid value.
if (instance.errors.hasFieldErrors('status')) {
instance.errors.rejectValue("status", "error.code.for.status",
[message(code: 'instance.label', default: 'Test Domain')] as Object[],
"Custom error message")
render(view: "edit", model: [instance: instance])
return
}
OR
// Will render error message corressponding to message code passed
if (instance.errors.hasFieldErrors('status')) {
instance.errors.rejectValue("status", "error.code.for.status")
render(view: "edit", model: [instance: instance])
return
}
OR
// Will render error message corressponding to message code passed
// and if not present will render default custom message passed.
if (instance.errors.hasFieldErrors('status')) {
instance.errors.rejectValue("status", "error.code.for.status",
"Custom error message")
render(view: "edit", model: [instance: instance])
return
}
精彩评论