Reputation: 585
How do I handle a server error in the middle of an Http message?
Assuming I already sent the header of the message and I am streaming the the body of the message, what do I do when I encounter an unexpected error.
I am also assuming this error was caused while generating the content and not a connection error.
(Greatly) Simplified Code:
// I can define any transfer encoding or header fields i need to.
send(header); // Sends the header to the Http client.
// Using an iterable instead of stream for code simplicity's sake.
Iterable<String> stream = getBodyStream();
Iterator<String> iterator = stream.iterator();
while (iterator.hasNext()) {
String string;
try {
string = iterator.next();
catch (Throwable error) { // Oops! an error generating the content.
// What do i do here? (In regards to the Http protocol)
}
send(string);
}
Is there a way to tell the client the server failed and should either retry or abandon the connection or am I sool?
The code is greatly simplified but I am only asking in regards to the protocol and not the exact code.
Thank You
Upvotes: 43
Views: 10540
Reputation: 39363
Partially quoting tigt's proposal to Marko.js, which was presumably informed by his issue on httpwg/http-core.
Transfer-Encoding: chunked
IETF Draft: HTTP/1.1 Messaging §8 Handling Incomplete Messages
If a chunked response doesn’t terminate with the zero-length end chunk, the client must assume that the response was incomplete — which at the very least, means a cache should double-check with the server before reusing the stored incomplete response.
RFC 7540 §5.4.2 Stream Error Handling
An HTTP/2 stream can signal an application error by sending a
RST_STREAM
frame with an error code of0x2 INTERNAL_ERROR
I didn't find anything more specific, but the current HTTP/3 RFC section on error handling seems to at least allow:
a generic error code (such as [...] INTERNAL_ERROR) can always be used in place of specific error codes.
Upvotes: 0
Reputation: 4519
One of the following should do it:
It depends on what you want your client to do with the data (keep it or throw it away). You may not be able to make changes on the client side so the last option will not work for example.
Here is some explanation about the different ways to close. TCP option SO_LINGER (zero) - when it's required.
Upvotes: 27
Reputation: 1387
I think the server should return a response code start with 5xx as per RFC 2616.
Server Error 5xx
Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. User agents SHOULD display any included entity to the user. These response codes are applicable to any request method.
Upvotes: -10