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.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With