REST Web Service: Acceptable HTTP response content

2020-07-18 03:27发布

I have been unable to find any documentation in the HTTP specifications that govern whether it is acceptable to generate a HTTP response include a human readable error message (e.g. content-type: text/plain) if an HTTP client has made an invalid HTTP request, and specified a request header that limits the acceptable response content types using an accept header.

Imagine a REST web service client issuing an invalid GET request to "http://myhost/validpath?illegalRequestParameter=rubbish", and including a request header "Accept: application/xml" or "Accept: application/vnd.ms-excel".

The server would respond with an HTTP status code in the 4XX series ("400 Bad Request", in this case). But how would the service be able to convey information to the client about the cause of the error?

I see the following options:

  1. Create a plaintext error message in the HTTP response content. Set response header "Content-type: text/plain" and include a descriptive error message in the response content. This would, however, break the HTTP client's "Accept" restriction.

  2. Don't include a HTTP response content. This is clearly valid, but not very helpful to the client that just knows that a "Client Error" occurred but has no way of knowing why (and reporting the reason in a client log file).

  3. Try to coerce an error message into an "Accept'able" MIME type. This is rarely possible. Even if the error message could be constructed as a valid application/xml type, it would likely break a web service contract (e.g. XML Schema conformance).

My question is: Is the above situation governed by existing HTTP specifications/standards?

References:

  1. HTTP Status Code Definitions: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  2. HTTP Header Field Definitions http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

1条回答
Root(大扎)
2楼-- · 2020-07-18 03:27

If the accept header is 'application/xml', then you should return your error message as xml. It will break the client, but that doesn't matter, the client isn't getting the information they requested anyway. At least the client is able to parse the error message...

查看更多
登录 后发表回答