Skip to content

Commit 901b66d

Browse files
committed
Android: more meaningful errors for non-200 HTTP responses
1 parent 70a9ef2 commit 901b66d

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

android/app/src/main/java/com/microsoft/codepush/react/CodePushUpdateManager.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,13 @@ public void downloadPackage(JSONObject updatePackage, String expectedBundleFileN
178178
}
179179

180180
connection.setRequestProperty("Accept-Encoding", "identity");
181+
182+
int responseCode = connection.getResponseCode();
183+
if (responseCode < 200 || responseCode >= 300) {
184+
throw new CodePushUnknownException("Error downloading update package. Response code: "
185+
+ responseCode + ". Response body: " + NetworkUtils.readStreamToString(connection.getErrorStream()));
186+
}
187+
181188
bin = new BufferedInputStream(connection.getInputStream());
182189

183190
long totalBytes = connection.getContentLength();
@@ -349,6 +356,13 @@ public void downloadAndReplaceCurrentBundle(String remoteBundleUrl, String bundl
349356
try {
350357
downloadUrl = new URL(remoteBundleUrl);
351358
connection = (HttpURLConnection) (downloadUrl.openConnection());
359+
360+
int responseCode = connection.getResponseCode();
361+
if (responseCode < 200 || responseCode >= 300) {
362+
throw new CodePushUnknownException("Error downloading update package. Response code: "
363+
+ responseCode + ". Response body: " + NetworkUtils.readStreamToString(connection.getErrorStream()));
364+
}
365+
352366
bin = new BufferedInputStream(connection.getInputStream());
353367
File downloadFile = new File(getCurrentPackageBundlePath(bundleFileName));
354368
downloadFile.delete();
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
@file:JvmName("NetworkUtils")
2+
3+
package com.microsoft.codepush.react
4+
5+
import java.io.InputStream
6+
7+
/**
8+
* Reads an InputStream to its end and returns the contents as a UTF-8 string,
9+
* closing the stream afterwards. Returns an empty string for a null stream (e.g.
10+
* HttpURLConnection.getErrorStream() when the server sent no error body).
11+
*/
12+
fun readStreamToString(inputStream: InputStream?): String {
13+
return inputStream?.bufferedReader()?.use { it.readText() } ?: ""
14+
}

0 commit comments

Comments
 (0)