views:

1159

answers:

3

I am just starting out with Grails, obviously. I've created my domain class and controller, added my own logic to the controller, and everything is working properly -- as long as nothing goes wrong.

My custom controller action looks like this:

def create = {
    try
    {
        // Get the parameters.
        def uid=params["uid"]
        def pwd=params["pwd"]
        if (!uid || !pwd)
        {
            throw new Exception('User ID and password are required')
        }
        /* other code */   
    }
    catch (Exception ex)
    {
        println ex.getMessage()
    }
}

My code (/* other code */) is working fine. When the exception is thrown, however, the error message is printed to the console and the browser throws a 404 error. Obviously, this isn't the way to go.

What's the correct way to do this?

TIA,

John

A: 

In your BootStrap.groovy file you can do this set up catch-all handlers for different Java Exceptions. Here is an article about it.

Sean A.O. Harney
+3  A: 

Based on the code snippet you provided, I guess what you really want is validation of some sort of user input (probably a form). If this is the case, throwing exceptions definitely isn't the way to go. You should only throw an exception if something exceptional (something unexpected, that usually shouldn't happen during normal operation) happens - by the way, this also holds for other programming languages.

Grails provides very good support for validating user inputs. Depending on the context, you should either define constraints in your domain classes, or use command objects and define constraints there (if the fields to be validated are not backed directly by a domain class). This way Grails validates the user input automatically against your constraints (there are many different kinds, such as size, blank/non-blank, or even RegExp constraints) and stores the errors and the corresponding messages in the domain class. You can then easily display the appropriate localized error messages in your form (view). It's good practice to display the errors right next to the input field they refer to.

Have a look at the Reference Documentation - especially chapter 7 (validation).

The 404 you are getting is probably not due to the (catched) exception, but rather because you don't have a view called create.gsp or a render/redirect call in your action.

I hope this answers your question or at least points you in the right direction. Good luck!

Daniel Rinser
A: 

As Daniel says, use constraints in your domain class instead and use the validate() method in your controller instead of throwing exceptions.

If validate() returns false, render the form again with an error message.

leebutts