Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: how to return error message from controller logic (i.e. not originating from domain property validation)?

Errors e.g. with bad user input can not always be reasonably checked using domain or command object validation.

E.g. when creating a "forgot password" functionality, I want to show an adequate message if the user enters a username which is not present in the database. So the controller action does something like this

...
def user = User.find{name==uname}
if(!user) {
    // user not found in db, output error and render view again
    render view: 'forgotPassword'
    return
}
// do reset password stuff
...

What should I do to display the error in the view within the <g:hasErros> tag?

flash.message (as the generated controllers/views do it) does not seem right to me, because I am not merely displaying an info message, but an error message. That's why I think the message should be handled by the <g:hasErros> tag and displayed like a domain validation error. (To the user, it is the same feedback level: "did not work due to bad input".

Creating a @Validateable command object does not seem right, too. IMHO, checking a value against the database is not actually the responsibility of validation within a command object? Or is it? Then it seems to be a little too complex to me.

So what is the best way to go? Other frameworks (e.g. Wicket) provide distinct methods like error(String msg) and info(String msg) which allow easy handling of feedback messages in the view. Is there a similar concept in Grails, which I just have not found yet?

like image 428
peterp Avatar asked Dec 11 '22 22:12

peterp


1 Answers

flash is just a Map and you can put whatever you want in it - strings, numbers, objects, etc. It's convenient since it only lasts one request, so it only temporarily pollutes the session. The convention in the generated GSPs is to use the message key, but it's just a convention.

If you want to store another message, store it in a different key:

flash.warning = '...'

or

flash.error = '...'

and retrieve it in the GSP like the other message.

like image 79
Burt Beckwith Avatar answered Dec 28 '22 06:12

Burt Beckwith