8.3.6 Mapping to Response Codes

Grails also lets you map HTTP response codes to controllers, actions or views. Just use a method name that matches the response code you are interested in:

  1. static mappings = {
  2. "403"(controller: "errors", action: "forbidden")
  3. "404"(controller: "errors", action: "notFound")
  4. "500"(controller: "errors", action: "serverError")
  5. }

Or you can specify custom error pages:

  1. static mappings = {
  2. "403"(view: "/errors/forbidden")
  3. "404"(view: "/errors/notFound")
  4. "500"(view: "/errors/serverError")
  5. }

Declarative Error Handling

In addition you can configure handlers for individual exceptions:

  1. static mappings = {
  2. "403"(view: "/errors/forbidden")
  3. "404"(view: "/errors/notFound")
  4. "500"(controller: "errors", action: "illegalArgument",
  5. exception: IllegalArgumentException)
  6. "500"(controller: "errors", action: "nullPointer",
  7. exception: NullPointerException)
  8. "500"(controller: "errors", action: "customException",
  9. exception: MyException)
  10. "500"(view: "/errors/serverError")
  11. }

With this configuration, an IllegalArgumentException will be handled by the illegalArgument action in ErrorsController, a NullPointerException will be handled by the nullPointer action, and a MyException will be handled by the customException action. Other exceptions will be handled by the catch-all rule and use the /errors/serverError view.

You can access the exception from your custom error handing view or controller action using the request’s exception attribute like so:

  1. class ErrorController {
  2. def handleError() {
  3. def exception = request.exception
  4. // perform desired processing to handle the exception
  5. }
  6. }
If your error-handling controller action throws an exception as well, you’ll end up with a StackOverflowException.