Fix spurious exceptions when client closes conncetion

If a HTTP handler throws an exception while processing a request we
automatically write a JSON error response. If the handler had already
started writing a response twisted throws an exception.

We should check for this case and simple abort the connection if there
was an error after the response had started being written.
This commit is contained in:
Erik Johnston 2018-09-20 13:44:20 +01:00
parent 3fd68d533b
commit b28a7ed503

View file

@ -84,10 +84,21 @@ def wrap_json_request_handler(h):
logger.info( logger.info(
"%s SynapseError: %s - %s", request, code, e.msg "%s SynapseError: %s - %s", request, code, e.msg
) )
respond_with_json(
request, code, e.error_dict(), send_cors=True, # Only respond with an error response if we haven't already started
pretty_print=_request_user_agent_is_curl(request), # writing, otherwise lets just kill the connection
) if request.startedWriting:
if request.transport:
try:
request.transport.abortConnection()
except Exception:
# abortConnection throws if the connection is already closed
pass
else:
respond_with_json(
request, code, e.error_dict(), send_cors=True,
pretty_print=_request_user_agent_is_curl(request),
)
except Exception: except Exception:
# failure.Failure() fishes the original Failure out # failure.Failure() fishes the original Failure out
@ -100,16 +111,26 @@ def wrap_json_request_handler(h):
request, request,
f.getTraceback().rstrip(), f.getTraceback().rstrip(),
) )
respond_with_json( # Only respond with an error response if we haven't already started
request, # writing, otherwise lets just kill the connection
500, if request.startedWriting:
{ if request.transport:
"error": "Internal server error", try:
"errcode": Codes.UNKNOWN, request.transport.abortConnection()
}, except Exception:
send_cors=True, # abortConnection throws if the connection is already closed
pretty_print=_request_user_agent_is_curl(request), pass
) else:
respond_with_json(
request,
500,
{
"error": "Internal server error",
"errcode": Codes.UNKNOWN,
},
send_cors=True,
pretty_print=_request_user_agent_is_curl(request),
)
return wrap_async_request_handler(wrapped_request_handler) return wrap_async_request_handler(wrapped_request_handler)