1

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?

tokosh
  • 1,772
  • 3
  • 20
  • 37
  • 1
    how about :response.sendError 403 – V H Jun 09 '14 at 10:12
  • @vahid: Thanks. This, however, gives me a 404 (whatever the error code) with a default response (not declared in url mappings). – tokosh Jun 09 '14 at 10:18
  • 1
    response.status = 403 render "some response" should work http://stackoverflow.com/questions/1429388/how-can-i-return-a-404-50x-status-code-from-a-grails-controller – V H Jun 09 '14 at 10:25
  • 1
    `response.sendError 403` works perfectly. Make sure you have created controller and action as in your URL mapping and rendered something from action. – MKB Jun 09 '14 at 10:31
  • Thanks both, vahid and user1690588, for reconfirming that this is the way. I left the exception, when I tried the "sendError". Does anyone of you want to post this as an answer? – tokosh Jun 09 '14 at 10:41
  • vahid should post it as answer as he is the first. – MKB Jun 09 '14 at 10:43
  • OK may be vahid is not interested. I have posted my answer. – MKB Jun 10 '14 at 03:38

1 Answers1

2

Try this

response.sendError 403

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

MKB
  • 7,587
  • 9
  • 45
  • 71