Search code examples
grailsgrails-controller

Grails: What is to set in the controller in order to reach the error handling in the URL mapping?


Using Grails 2.3.9

In the controller I'm trying to make a request go through the error handling declared in the URL mappings. I've read the docs, but I still don't get how this works.

From the example of the documentation:

static mappings = {
   "403"(controller: "errors", action: "forbidden")
   "404"(controller: "errors", action: "notFound")
   "500"(controller: "errors", action: "serverError")
}

For example in a controller:

def update() {
    // do some tests
    if(forbidden) {
        // Go to 403
        //response.status = response.SC_FORBIDDEN
        render status: 403 
        return
    }
    // deal with normal case
}

What do I have to do in the controller in order to land on the 403 action? Doing response.status = response.SC_FORBIDDEN or render status: 403 is not working.

I was able to achieve going through mappings 403 by throwing a custom exception ForbiddenException while the url mappings would contain:

"403"(controller: "errors", action: "forbidden", exception: ForbiddenException)

However, I guess, reaching the error controller through another controller should also go with throwing an exception for each case, no?


Solution

  • Try this

    response.sendError 403
    

    and make sure you have created controller and action as in your URL mapping and rendered something from action.