简体   繁体   中英

Grails - How can I get a single error message

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.

Any 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')

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
}

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM