Monday, November 17, 2008

Grails and 404 Page Not Found

Every good website should have a nice 404 page. This is the page that is displayed when your customers or clients navigate to a destination that does not exist, by typing an invalid URL.

Grails does not give you a nice implementation of 404 error (or any other than 500 error). You need to implement it yourself.

If you search the Internet for examples of how to implement 404 Page Not Found error in Grails, most of the results talk about the following scenario:

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

The previous piece of declaration resides inside UrlMappings.groovy and what it means is that if an error occurs, the request is redirected to errors controller which will execute in case of 404 the notFound action. This action could be as simple as

def notFound = {

This is all good, but if it is all you need to do (render a view - notFound.gsp) you may as well express it declaratively inside UrlMappings.groovy

class UrlMappings {
static mappings = {

This way you won't need a controller class at all. All you need are GSP files in the locations declared in the mappings.


1 comment:

hyunjungsoh said...

Hello, Thank you for posting this. :)

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.