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

前端 未结 4 1688
傲寒
傲寒 2020-12-14 14:11

I have a controller that needs to return a 404 page and status code on certain conditions. I can\'t seem to find out how to do this in Grails. A coworker recommended this me

相关标签:
4条回答
  • 2020-12-14 14:24

    I don't know what version this 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

    0 讨论(0)
  • 2020-12-14 14:30

    response.sendError(404) will work with Grails UrlMappings whereas response.status = 404 does not for some reason. This is useful if you want to render a custom 404 error page, as opposed to just sending 404 back to the browser.

    0 讨论(0)
  • 2020-12-14 14:45

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

    response.status = 404;
    

    I've used this successfully myself and have seen others do it this way too. Since it's just a setter, you can also do other stuff after setting the status. Whichever status you set last will be what the HttpServletResponse uses when it actually sends the response back to the client.

    0 讨论(0)
  • 2020-12-14 14:50

    response.sendError and response.setStatus are the only two ways I know of. If you static import HttpServletResponse, then it's not that 'un-grails-like'.

    0 讨论(0)
提交回复
热议问题