问题
When a TCP connection gets cancelled by the client while making a HTTP request, I'd like to stop doing any work on the server and return an empty response. What HTTP status code should such a response return?
回答1:
To be consistent I would suggest 400 Bad Request
now if your backend apps are capable of identifying when the client gets disconnected or if you reject or close the connection, probably you could return Nginx' non-standard code 499 or 444.
499 Client Closed Request Used when the client has closed the request before the server could send a response.
444 No Response Used to indicate that the server has returned no information to the client and closed the connection.
回答2:
HTTP (1.0/1.1) doesn't have a means to cancel a request. All that a client can do if it no longer wants the response is to close the connection and hope that the server contains an optimization to stop working on a response that can no longer be delivered. Since the connection is now closed, no response nor status code can actually be delivered to the client and so any code you "return" is only for your own satisfaction. I'd personally pick something in the 4xx range1 since the "fault" - the reason you can no longer deliver a response - is due to the client.
HTTP 2.0 does allow an endpoint to issue END_STREAM
or RST_STREAM
to indicate that they are no longer interested in one stream without tearing down the whole connection. However, they're meant to just ignore any further HEADERS
or DATA
sent on that stream and so even though you may theoretically deliver a status code, the client is still going to completely ignore it.
1Probably 400 itself since I can't identify a more specific error that seems entirely appropriate.
回答3:
There are just a few plausible choices (aside from 500, of course):
202 Accepted
You haven't finished processing, and you never will.
This is appropriate only if, in your application domain, the original requestor "expects" that not all requests will be satisfied.
409 Conflict
…between making and cancelling the request.
This is only weakly justified: your situation does not involve one client making a request based on out of date information, since the cancellation had not yet occurred.
503 Service Unavailable
The service is in fact unavailable for this one request (because it was cancelled!).
The general argument of "report an error as an error" favors 409 or 503. So 503 it is by default.
回答4:
There really is little to do. Quoting from RFC 7230, section 6.5:
A client, server, or proxy MAY close the transport connection at any time.
That is happening at TCP-, not HTTP-level. Just stop processing the connection. A status code will confer little meaning here as the intent of an incomplete/broken request is mere speculation. Besides, there will be no means to transport it across to the client.
来源:https://stackoverflow.com/questions/46234679/what-is-the-correct-http-status-code-for-a-cancelled-request