Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: Return 404 & show my 'Not Found' page for invalid id

Tags:

grails

What's the best way to handle invalid ids in a Grails controller action?

When MyDomainClass.get(params['i']) returns null in my controller action I want the user to see my custom 'Not Found' page and for a 404 HTTP response code to be returned - I can't figure out the cleanest way to do this.

Thanks.

like image 203
Martin Dow Avatar asked Jan 21 '11 15:01

Martin Dow


2 Answers

I've used the following in my controllers, where 'notFound' is a custom 404 page:

def show = {
        def referenceData = ReferenceData.get( params.id )    
        if (referenceData)
        { return [ referenceData : referenceData ] }
        else 
        { redirect(uri:'/notFound') }
    }

I also mapped the custom error pages in UrlMapping.groovy, something like

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

or

static mappings = {
   "403"(view: "/errors/forbidden")
   "404"(view: "/errors/notFound")
   "500"(view: "/errors/serverError")
}

Grails Docs - mapping to response codes

like image 166
R. Valbuena Avatar answered Nov 23 '22 19:11

R. Valbuena


EDIT - I apologize for misreading your question. the render method takes a status code. So in the controller, if nothing is found, try

render status: 404

or

render view: you_not_found_view

or both (in one render call).

like image 28
hvgotcodes Avatar answered Nov 23 '22 19:11

hvgotcodes