Skip to content

Commit 11cff2e

Browse files
committed
Improve http error handling
1 parent b2a1b03 commit 11cff2e

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

src/main/java/io/ipfs/api/IPFS.java

+14-10
Original file line numberDiff line numberDiff line change
@@ -734,12 +734,16 @@ HTTP endpoint (usually :5001). Applications integrating on top of the
734734
} catch (ConnectException e) {
735735
throw new RuntimeException("Couldn't connect to IPFS daemon at "+target+"\n Is IPFS running?");
736736
} catch (IOException e) {
737-
InputStream errorStream = conn.getErrorStream();
738-
String err = errorStream == null ? e.getMessage() : new String(readFully(errorStream));
739-
throw new RuntimeException("IOException contacting IPFS daemon.\n"+err+"\nTrailer: " + conn.getHeaderFields().get("Trailer"), e);
737+
throw extractError(e, conn);
740738
}
741739
}
742740

741+
public static RuntimeException extractError(IOException e, HttpURLConnection conn) {
742+
InputStream errorStream = conn.getErrorStream();
743+
String err = errorStream == null ? e.getMessage() : new String(readFully(errorStream));
744+
return new RuntimeException("IOException contacting IPFS daemon.\n"+err+"\nTrailer: " + conn.getHeaderFields().get("Trailer"), e);
745+
}
746+
743747
private void getObjectStream(InputStream in, Consumer<byte[]> processor, Consumer<IOException> error) {
744748
byte LINE_FEED = (byte)10;
745749

@@ -789,11 +793,7 @@ private static InputStream getStream(URL target, int connectTimeoutMillis, int r
789793
try {
790794
return conn.getInputStream();
791795
} catch (IOException e) {
792-
e.printStackTrace();
793-
InputStream errorStream = conn.getErrorStream();
794-
String err = errorStream == null ? e.getMessage() : new String(readFully(errorStream));
795-
List<String> trailer = conn.getHeaderFields().get("Trailer");
796-
throw new RuntimeException("IOException contacting IPFS daemon.\n"+err+"\nTrailer: " + trailer, e);
796+
throw extractError(e, conn);
797797
}
798798
}
799799

@@ -812,8 +812,12 @@ private static byte[] post(URL target, byte[] body, Map<String, String> headers,
812812
out.flush();
813813
out.close();
814814

815-
InputStream in = conn.getInputStream();
816-
return readFully(in);
815+
try {
816+
InputStream in = conn.getInputStream();
817+
return readFully(in);
818+
} catch (IOException e) {
819+
throw extractError(e, conn);
820+
}
817821
}
818822

819823
private static final byte[] readFully(InputStream in) {

0 commit comments

Comments
 (0)