From ea8117eb795bb1ec5a18200a0237f605fd8700a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janko=20Marohni=C4=87?= Date: Sat, 14 Oct 2017 23:17:12 +0200 Subject: [PATCH] Raise ConnectionError when writing to socket fails Writing to the TCP socket can also fail with various exceptions, just like when opening or reading from it. For example, it happened to me that an Errno::EPIPE exceptions was raised during file upload, presumably because the server closed the connection early. In order to be consistent with re-raising low-level exceptions as HTTP::ConnectionError when opening or reading from the TCP socket, we also add the same behaviour when writing to the socket. --- lib/http/request/writer.rb | 2 ++ spec/lib/http/request/writer_spec.rb | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/lib/http/request/writer.rb b/lib/http/request/writer.rb index ab56b013..b2f383fe 100644 --- a/lib/http/request/writer.rb +++ b/lib/http/request/writer.rb @@ -100,6 +100,8 @@ def write(data) break unless data.bytesize > length data = data.byteslice(length..-1) end + rescue IOError, SocketError, SystemCallError => ex + raise ConnectionError, "error writing to socket: #{ex}", ex.backtrace end end end diff --git a/spec/lib/http/request/writer_spec.rb b/spec/lib/http/request/writer_spec.rb index 0cfa658a..62780a6f 100644 --- a/spec/lib/http/request/writer_spec.rb +++ b/spec/lib/http/request/writer_spec.rb @@ -74,5 +74,15 @@ ].join end end + + context "when writing to socket raises an exception" do + before do + expect(io).to receive(:write).and_raise(Errno::EPIPE) + end + + it "raises a ConnectionError" do + expect { writer.stream }.to raise_error(HTTP::ConnectionError) + end + end end end