We are designing a REST application in Tomcat which should be cross-domain accessible. So for all responses we include the famous CORS header:
Access-Control-Allow-Origin: *
However, because it is a REST service, the server sometimes returns HTTP responses that are not 200 OK. E.g. 400, 403, 404, 405. One problem that we are having is that currently these responses do not contain the CORS header, and therefore cannot be interpreted by a cross-domain web client. It turns out it is a common issue: http://www.w3.org/wiki/Talk:CORS_Enabled
What is a good way in Tomcat to return non-200 responses with custom body, headers, etc, so that we can set the CORS header?
Our solution is DYI: catch all Exceptions and call a Utility method that writes the
HTTPServletResponseof the servlet directly with the body being the message of theExceptionOn the
HTTPServletResponseobject, you can specify all you need, including the HTTP status code (I guess you use 400 for REST as is the norm), and all necessary headers including CORS headers.