How to properly send an HTTP message to the client
I'm working on a RESTful web service in Java. I need a good way to send error messages to the client if something's wrong.
According to the Javadoc, HttpServletResponse.setStatus(int status, String message)
is deprecated "due to ambiguous meaning of the message parameter."
Is there a preferred way to set the status message or "reason phrase" of the response? The sendError(int, String)
method doesn't do it.
EDIT:
To clarify, I want to modify the HTTP status line, i.e. "HTTP/1.1 404 Not Found"
, not the body content. Specifically, I'd like to send responses like "HTTP/1.1 400 Missing customerNumber parameter"
.
Solution 1:
I don't think any RESTful client would expect to look at the reason phrase to figure out what went wrong; most RESTful services I've seen/used will send the standard status info and an expanded message in the body of the response. sendError(int, String)
is ideal for that situation.
Solution 2:
If you're using Tomcat, see the setting org.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER:
http://tomcat.apache.org/tomcat-5.5-doc/config/systemprops.html
- If this is true custom HTTP status messages will be used within HTTP headers. Users must ensure that any such message is ISO-8859-1 encoded, particularly if user provided input is included in the message, to prevent a possible XSS vulnerability. If not specified the default value of false will be used.
See this page for some detail on the original vulnerability:
http://www.securityfocus.com/archive/1/archive/1/495021/100/0/threaded
Solution 3:
After your clarification, I tried this in Tomcat. Executing
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "message goes here");
returns
HTTP/1.1 400 message goes here
as the first line in the response.
There must be a problem with the servlet container you are using.
Solution 4:
I'm not quite familiar with the 'best practices' around REST. But I know the concept is based on HTTP and how it is supposed to work out naturally. So how about using a mime type and simple text inside the body for an application error, like 'application/myapp-exception' and some 'Bla bla'? You can provide a client library for that.
I would not use HTTP response codes for application errors. Because I like to know what's failing: whether it is my application or my HTTP server.
(I hope, I'll see some best practice advices here, too.)