Once the server has sent the client a status bar (the very first response line), you can no longer change the response status code. Many servers delay sending a response, buffering it internally until the buffer is full. As long as the buffer fills up, you can still change your mind about the answer.
If your client has access to response headers, you can use the fact that encoded encoding allows the server to add a trailer with headers after the body with encoded encoding. Thus, your server, faced with an error, can gracefully stop sending the body, and then send a trailer that sets some header for some value. Then your client will interpret the presence of this header as a sign that an error has occurred.
source