14

I am sending large amount of data in my response to the client in chunked transfer encoding format.

How should I be dealing with any errors that occur midway during writing of the response?

I would like to know if there is any HTTP Spec recommended practice regarding this for clients to know that indeed the response is not a successful one but that the server ran into some issue.

Kiran
  • 56,921
  • 15
  • 176
  • 161

2 Answers2

12

Once you have started sending the HTTP headers to the client, you can't send anything else. You have to finish sending the response you intended to send, ie the chunked data and associated headers. If an error occurs midway through that, there is no way to report that error to the client. All you can do is close the connection. Either the client does not receive all of the headers, or it does not receive the terminating 0-length chunk at the end of the response. Either way is enough for the client to know that the server encountered an error during sending.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thanks Remy. Yeah...right, I am aware that headers are sent first and there is no way to modify them once we start writing to the stream. As you suggested, I currently close the connection, but wanted to know if there is any other way that HTTP Spec says about how one could let the client know about it. The 0-length chunk interesting, I will check to see If I can do something in that area. – Kiran Jun 20 '13 at 18:04
  • 1
    There are only two ways you would be able to let the client know that something went wrong. Close the connection (which is what you should do) since anything other than receiving the last 0-length chunk is an error, or else put a custom HTTP header in the chunked footer after sending the last 0-lenth chunk. Most clients will likely ignore such a header though, but if you are writing your own client then you can look for that header. – Remy Lebeau Jun 20 '13 at 21:30
1

Chunked responses can use trailer header with some integrity check or post-processing status. This may be better than closing the connection as described in accepted answer because you can have custom error message. However, you only benefit from that if you have control of both server and client.

Matas
  • 820
  • 9
  • 18
  • Can you share some example of a client that support Trailer? Actually, I have not found it and think that the Trailer specification does not work in browsers. See this answer for more information https://stackoverflow.com/a/46374454/4778628. – Den Jun 15 '22 at 15:34