I’m building an httpserver as part of my academic java course,
The server should only support basic GET and POST requests.
I was wondering if there’s an elegant way to handle an error which occures in the middle of writing an html file stream content (and after I’ve already sent the response headers) into the HttpServer output stream.
By elegant way I refer to showing or redirecting the user to a “Internal Server Error” error page.
I tried re-sending the http response headers with 501 error code, but java throws an exception which claims that the headers were already sent…
One fix would be to read the file’s contents into memory, and only then sending the headers and the content, but other problems can arise, and furthermore, I don’t want to load huge files into the memory before sending them out as a response.
Once the response status is sent on the wire, it cannot be changed. So if you sent a
200 OKresponse, you cannot change your mind afterwards. As you found, this presents a problem in case of errors that occur mid response.As far as I know, the only think you can do is to send a chunked response. See section 3.6.1 of RFC 2616:
The purpose of this trailer is to give information about the entity body that cannot be calculated before the entity body is sent. However, section 7.1 allows any header to be included in this trailer:
So while you can signal that an error has occurred mid response, it must be conventioned between the two parts how this is signaled. You cannot, in general, use any method you can assume the client will understand as signaling an error condition.
Ending the connection prematurely in a message with a
Content-lengthheader is an option, but one that is explicitly forbidden:That said, while the server must not send a message shorter than he advertises, the client must check for this error condition and reported as such (and proxies may even cache this partial response).