How can I return a 404 / 50x status code from a Grails controller?

I have a controller that needs to return a 404 page and a status code under certain conditions. I can't seem to figure out how to do this in Grail. The employee recommended this method:

response.sendError(HttpServletResponse.SC_NOT_FOUND) 

which works great, but not very similar to Grails. I know that the Rails rendering method takes a state argument, but Grails rendering does not have this functionality. Is there something I'm missing, what is the best way to do this?

+51
error-handling grails groovy
Sep 15 '09 at 20:18
source share
4 answers

Setting the status of a response with its own statement is good enough. It doesn't look too ugly and pretty simple:

 response.status = 404; 

I have successfully used this, and have seen others do it this way . Since this is just a setter, you can also do other things after setting the status. Whatever status you set last will be used by HttpServletResponse when it actually sends a response to the client.

+48
Oct 06 '09 at 22:20
source share

response.sendError(404) will work with Grails UrlMappings , while response.status = 404 will not for some reason. This is useful if you want to display the 404 error page, and not just send 404 back to the browser.

+42
Mar 05 2018-11-21T00:
source share

I don't know which version it started in, but in Grails 2.2.1 you can do:

 render(status: 503, text: 'Failed to do stuff.') 

http://grails.org/doc/2.2.1/ref/Controllers/render.html

+41
Jun 03 '13 at 16:05
source share

response.sendError and response.setStatus are just two of the ways that I know of. If you are a static import HttpServletResponse , then this is not something that is "non-granite".

+8
Sep 15 '09 at 10:40
source share



All Articles