summary refs log tree commit diff
path: root/synapse/http/server.py
diff options
context:
space:
mode:
authorMark Haines <mark.haines@matrix.org>2016-02-12 13:46:59 +0000
committerMark Haines <mark.haines@matrix.org>2016-02-12 13:46:59 +0000
commit58c9f206929560044fccae84c36fdd89724ccfc0 (patch)
tree1fc9e3c4ba992e6c35efb68dc9a62a7fa021295a /synapse/http/server.py
parentMerge branch 'master' of github.com:matrix-org/synapse into develop (diff)
downloadsynapse-58c9f206929560044fccae84c36fdd89724ccfc0.tar.xz
Catch the exceptions thrown by twisted when you write to a closed connection
Diffstat (limited to 'synapse/http/server.py')
-rw-r--r--synapse/http/server.py21
1 files changed, 20 insertions, 1 deletions
diff --git a/synapse/http/server.py b/synapse/http/server.py
index a90e2e1125..b17b190ee5 100644
--- a/synapse/http/server.py
+++ b/synapse/http/server.py
@@ -367,10 +367,29 @@ def respond_with_json_bytes(request, code, json_bytes, send_cors=False,
                           "Origin, X-Requested-With, Content-Type, Accept")
 
     request.write(json_bytes)
-    request.finish()
+    finish_request(request)
     return NOT_DONE_YET
 
 
+def finish_request(request):
+    """ Finish writing the response to the request.
+
+    Twisted throws a RuntimeException if the connection closed before the
+    response was written but doesn't provide a convenient or reliable way to
+    determine if the connection was closed. So we catch and log the RuntimeException
+
+    You might think that ``request.notifyFinish`` could be used to tell if the
+    request was finished. However the deferred it returns won't fire if the
+    connection was already closed, meaning we'd have to have called the method
+    right at the start of the request. By the time we want to write the response
+    it will already be too late.
+    """
+    try:
+        request.finish()
+    except RuntimeError as e:
+        logger.info("Connection disconnected before response was written: %r", e)
+
+
 def _request_user_agent_is_curl(request):
     user_agents = request.requestHeaders.getRawHeaders(
         "User-Agent", default=[]