1

Say that an error occurs when I'm in the middle of sending a chunked response from my http server that I'm writing in Node.js. There's no way to send an error message to the client at this point, and I figure that this answer is correct on what to do in this situation:

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.

So the question is, how do I do this on my http.ServerResponse object? I can't call end, because then the client will think everything went well, and there is no close method. There is a 'close' event, but I get the feeling that's something I'm supposed to listen for in this context, not emit myself, right?

Community
  • 1
  • 1
njlarsson
  • 2,128
  • 1
  • 18
  • 27

1 Answers1

0

I do it in the following manner:

function respDestroy()
{
    this._socket.destroy();
}

function respReply(message, close)
{
    if (!close)
        this.end(message);
    else
        this.end(message, function(){ this.destroy(); });
}

server.on('request', 
    function(req, resp)
    {
        resp._socket = resp.socket; // `socket` field is nulled after each `end()`
        resp.destroy = respDestroy;
        resp.reply = respReply;
        ...
    });

You can modify respReply to accept status code and status message as well.

Fr0sT
  • 2,959
  • 2
  • 25
  • 18
  • Ok, so resp has a socket field? Sorry if I'm blind and/or stupid, but where is this stated in the documentation? – njlarsson Apr 22 '17 at 13:32
  • 1
    @njlarsson yes it has since some version but it's not mentioned in docs yet (you can check by yourself with `console.log(resp.socket)`. Depending on your Node version you can use it or `req`'s field - they're the same. Note that the very field `socket` couldn't be utilized as it is nulled before callback is invoked. – Fr0sT Apr 24 '17 at 07:18