Skip to content

Commit

Permalink
[SDK-2171] - [Android] Improve client-side network error logging (#1144)
Browse files Browse the repository at this point in the history
  • Loading branch information
gdeluna-branch authored Nov 10, 2023
1 parent cddc84b commit 91fc017
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,7 @@ public void onSuccess(int responseCode) {

@Override
public void onFailure(Exception e) {
Log.d("BranchSDK_Tester", e.toString());
Toast.makeText(getApplicationContext(), "Error sending Branch Commerce Event: " + e.toString(), Toast.LENGTH_SHORT).show();
}
});
Expand Down
13 changes: 8 additions & 5 deletions Branch-SDK/src/main/java/io/branch/referral/BranchError.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
public class BranchError {

String errorMessage_ = "";
int errorCode_ = ERR_BRANCH_NO_CONNECTIVITY;

int errorCode_ = ERR_OTHER;
/* Error processing request since session not initialised yet. */
public static final int ERR_NO_SESSION = -101;
/* Error processing request since app doesn't have internet permission. */
Expand Down Expand Up @@ -42,6 +41,10 @@ public class BranchError {
public static final int ERR_IMPROPER_REINITIALIZATION = -119;
/* Request task timed out before completing*/
public static final int ERR_BRANCH_TASK_TIMEOUT = -120;
/* Error when network request is made on main thread */
public static final int ERR_NETWORK_ON_MAIN = -121;
/* General error reporting */
public static final int ERR_OTHER = -122;

/**
* <p>Returns the message explaining the error.</p>
Expand Down Expand Up @@ -88,7 +91,7 @@ private String initErrorCodeAndGetLocalisedMessage(int statusCode) {
String errMsg;
if (statusCode == ERR_BRANCH_NO_CONNECTIVITY) {
errorCode_ = ERR_BRANCH_NO_CONNECTIVITY;
errMsg = " Branch API Error: poor network connectivity. Please try again later.";
errMsg = " Check network connectivity or DNS settings.";
} else if (statusCode == ERR_BRANCH_KEY_INVALID) {
errorCode_ = ERR_BRANCH_KEY_INVALID;
errMsg = " Branch API Error: Please enter your branch_key in your project's manifest file first.";
Expand Down Expand Up @@ -142,8 +145,8 @@ private String initErrorCodeAndGetLocalisedMessage(int statusCode) {
errorCode_ = ERR_BRANCH_TASK_TIMEOUT;
errMsg = " Task exceeded timeout.";
} else {
errorCode_ = ERR_BRANCH_NO_CONNECTIVITY;
errMsg = " Check network connectivity and that you properly initialized.";
errorCode_ = ERR_OTHER;
errMsg = " See exception message or logs for more details. ";
}
return errMsg;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -439,11 +439,11 @@ private void awaitTimedBranchPostTask(CountDownLatch latch, int timeout, BranchP
try {
if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
postTask.cancel(true);
postTask.onPostExecuteInner(new ServerResponse(postTask.thisReq_.getRequestPath(), ERR_BRANCH_TASK_TIMEOUT, ""));
postTask.onPostExecuteInner(new ServerResponse(postTask.thisReq_.getRequestPath(), ERR_BRANCH_TASK_TIMEOUT, "", ""));
}
} catch (InterruptedException e) {
postTask.cancel(true);
postTask.onPostExecuteInner(new ServerResponse(postTask.thisReq_.getRequestPath(), ERR_BRANCH_TASK_TIMEOUT, ""));
postTask.onPostExecuteInner(new ServerResponse(postTask.thisReq_.getRequestPath(), ERR_BRANCH_TASK_TIMEOUT, "", e.getMessage()));
}
}

Expand Down Expand Up @@ -510,7 +510,7 @@ protected ServerResponse doInBackground(Void... voids) {
// update queue wait time
thisReq_.doFinalUpdateOnBackgroundThread();
if (Branch.getInstance().getTrackingController().isTrackingDisabled() && !thisReq_.prepareExecuteWithoutTracking()) {
return new ServerResponse(thisReq_.getRequestPath(), BranchError.ERR_BRANCH_TRACKING_DISABLED, "");
return new ServerResponse(thisReq_.getRequestPath(), BranchError.ERR_BRANCH_TRACKING_DISABLED, "", "");
}
String branchKey = Branch.getInstance().prefHelper_.getBranchKey();
ServerResponse result;
Expand Down Expand Up @@ -641,6 +641,7 @@ private void onRequestSuccess(ServerResponse serverResponse) {
}

void onRequestFailed(ServerResponse serverResponse, int status) {
BranchLogger.v("onRequestFailed " + serverResponse.getMessage());
// If failed request is an initialisation request (but not in the intra-app linking scenario) then mark session as not initialised
if (thisReq_ instanceof ServerRequestInitSession && PrefHelper.NO_STRING_VALUE.equals(Branch.getInstance().prefHelper_.getSessionParams())) {
Branch.getInstance().setInitState(Branch.SESSION_STATE.UNINITIALISED);
Expand All @@ -653,7 +654,7 @@ void onRequestFailed(ServerResponse serverResponse, int status) {
//On Network error or Branch is down fail all the pending requests in the queue except
//for request which need to be replayed on failure.
ServerRequestQueue.this.networkCount_ = 0;
thisReq_.handleFailure(status, serverResponse.getFailReason());
thisReq_.handleFailure(status, serverResponse.getFailReason() + " " + serverResponse.getMessage());
}

boolean unretryableErrorCode = (400 <= status && status <= 451) || status == BranchError.ERR_BRANCH_TRACKING_DISABLED;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,20 @@ public class ServerResponse {
*/
private String requestId_;

private String message_;

/**
* <p>Main constructor method for the {@link ServerResponse} class that allows for the instantiation
* of a server response object as a direct result of a server call.</p>
*
* @param tag A {@link String} value of the <i>Tag</i> attribute of the current link.
* @param statusCode {@link Integer} value of the HTTP status code.
*/
public ServerResponse(String tag, int statusCode, String requestId) {
public ServerResponse(String tag, int statusCode, String requestId, String message) {
tag_ = tag;
statusCode_ = statusCode;
requestId_ = requestId;
message_ = message;
}

/**
Expand Down Expand Up @@ -136,4 +139,7 @@ public String getFailReason() {
return causeMsg;
}

public String getMessage() {
return message_;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public final ServerResponse make_restful_get(String url, JSONObject params, Stri
if (addCommonParams(params, branchKey)) {
modifiedUrl += this.convertJSONtoString(params);
} else {
return new ServerResponse(tag, BranchError.ERR_BRANCH_KEY_INVALID, "");
return new ServerResponse(tag, BranchError.ERR_BRANCH_KEY_INVALID, "", "");
}

long reqStartTime = System.currentTimeMillis();
Expand All @@ -104,11 +104,7 @@ public final ServerResponse make_restful_get(String url, JSONObject params, Stri
BranchResponse response = doRestfulGet(modifiedUrl);
return processEntityForJSON(response, tag, response.requestId);
} catch (BranchRemoteException branchError) {
if (branchError.branchErrorCode == BranchError.ERR_BRANCH_REQ_TIMED_OUT) {
return new ServerResponse(tag, BranchError.ERR_BRANCH_REQ_TIMED_OUT, "");
} else { // All other errors are considered as connectivity error
return new ServerResponse(tag, BranchError.ERR_BRANCH_NO_CONNECTIVITY, "");
}
return new ServerResponse(tag, branchError.branchErrorCode, "", branchError.branchErrorMessage);
} finally {
// Add total round trip time
if (Branch.getInstance() != null) {
Expand All @@ -132,7 +128,7 @@ public final ServerResponse make_restful_post(JSONObject body, String url, Strin
body = body != null ? body : new JSONObject();

if (!addCommonParams(body, branchKey)) {
return new ServerResponse(tag, BranchError.ERR_BRANCH_KEY_INVALID, "");
return new ServerResponse(tag, BranchError.ERR_BRANCH_KEY_INVALID, "", "");
}
BranchLogger.v("posting to " + url);
BranchLogger.v("Post value = " + body.toString());
Expand All @@ -141,11 +137,7 @@ public final ServerResponse make_restful_post(JSONObject body, String url, Strin
BranchResponse response = doRestfulPost(url, body);
return processEntityForJSON(response, tag, response.requestId);
} catch (BranchRemoteException branchError) {
if (branchError.branchErrorCode == BranchError.ERR_BRANCH_REQ_TIMED_OUT) {
return new ServerResponse(tag, BranchError.ERR_BRANCH_REQ_TIMED_OUT, "");
} else { // All other errors are considered as connectivity error
return new ServerResponse(tag, BranchError.ERR_BRANCH_NO_CONNECTIVITY, "");
}
return new ServerResponse(tag, branchError.branchErrorCode, "", branchError.branchErrorMessage);
} finally {
if (Branch.getInstance() != null) {
int brttVal = (int) (System.currentTimeMillis() - reqStartTime);
Expand Down Expand Up @@ -175,7 +167,7 @@ private ServerResponse processEntityForJSON(BranchResponse response, String tag,

int statusCode = response.responseCode;

ServerResponse result = new ServerResponse(tag, statusCode, requestId);
ServerResponse result = new ServerResponse(tag, statusCode, requestId, "");
if(!TextUtils.isEmpty(requestId)){
BranchLogger.v(String.format(Locale.getDefault(), "Server returned: [%s] Status: [%d]; Data: %s", requestId, statusCode, responseString));
} else {
Expand Down Expand Up @@ -285,7 +277,8 @@ public BranchResponse(@Nullable String responseData, int responseCode) {
* see {@link #doRestfulGet(String)} and {@link #doRestfulPost(String, JSONObject)}
*/
public static class BranchRemoteException extends Exception {
private int branchErrorCode = BranchError.ERR_BRANCH_NO_CONNECTIVITY;
private int branchErrorCode;
private String branchErrorMessage;

/**
* Creates BranchRemoteException
Expand All @@ -296,6 +289,11 @@ public static class BranchRemoteException extends Exception {
public BranchRemoteException(int errorCode) {
branchErrorCode = errorCode;
}

public BranchRemoteException(int errorCode, String errorMessage) {
branchErrorCode = errorCode;
branchErrorMessage = errorMessage;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import android.net.TrafficStats;
import android.os.NetworkOnMainThreadException;
import android.util.Base64;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
Expand Down Expand Up @@ -101,8 +102,7 @@ private BranchResponse doRestfulGet(String url, int retryNumber) throws BranchRe
}
} catch (SocketException ex) {
BranchLogger.v("Http connect exception: " + ex.getMessage());
throw new BranchRemoteException(BranchError.ERR_BRANCH_NO_CONNECTIVITY);

throw new BranchRemoteException(BranchError.ERR_BRANCH_NO_CONNECTIVITY, ex.getMessage());
} catch (SocketTimeoutException ex) {
// On socket time out retry the request for retryNumber of times
if (retryNumber < prefHelper.getRetryCount()) {
Expand All @@ -114,7 +114,7 @@ private BranchResponse doRestfulGet(String url, int retryNumber) throws BranchRe
retryNumber++;
return doRestfulGet(url, retryNumber);
} else {
throw new BranchRemoteException(BranchError.ERR_BRANCH_REQ_TIMED_OUT);
throw new BranchRemoteException(BranchError.ERR_BRANCH_REQ_TIMED_OUT, ex.getMessage());
}
} catch(InterruptedIOException ex){
// When the thread times out before or while sending the request
Expand All @@ -127,11 +127,11 @@ private BranchResponse doRestfulGet(String url, int retryNumber) throws BranchRe
retryNumber++;
return doRestfulGet(url, retryNumber);
} else {
throw new BranchRemoteException(BranchError.ERR_BRANCH_TASK_TIMEOUT);
throw new BranchRemoteException(BranchError.ERR_BRANCH_TASK_TIMEOUT, ex.getMessage());
}
} catch (IOException ex) {
BranchLogger.v("Branch connect exception: " + ex.getMessage());
throw new BranchRemoteException(BranchError.ERR_BRANCH_NO_CONNECTIVITY);
throw new BranchRemoteException(BranchError.ERR_BRANCH_NO_CONNECTIVITY, ex.getMessage());
} finally {
if (connection != null) {
connection.disconnect();
Expand Down Expand Up @@ -223,6 +223,7 @@ private BranchResponse doRestfulPost(String url, JSONObject payload, int retryNu


} catch (SocketTimeoutException ex) {
BranchLogger.v("Encountered exception while attempting network request: " + Log.getStackTraceString(ex));
// On socket time out retry the request for retryNumber of times
if (retryNumber < prefHelper.getRetryCount()) {
try {
Expand All @@ -233,9 +234,10 @@ private BranchResponse doRestfulPost(String url, JSONObject payload, int retryNu
retryNumber++;
return doRestfulPost(url, payload, retryNumber);
} else {
throw new BranchRemoteException(BranchError.ERR_BRANCH_REQ_TIMED_OUT);
throw new BranchRemoteException(BranchError.ERR_BRANCH_REQ_TIMED_OUT, ex.getMessage());
}
} catch(InterruptedIOException ex){
BranchLogger.v("Encountered exception while attempting network request: " + Log.getStackTraceString(ex));
// When the thread times out before or while sending the request
if (retryNumber < prefHelper.getRetryCount()) {
try {
Expand All @@ -246,11 +248,12 @@ private BranchResponse doRestfulPost(String url, JSONObject payload, int retryNu
retryNumber++;
return doRestfulPost(url, payload, retryNumber);
} else {
throw new BranchRemoteException(BranchError.ERR_BRANCH_TASK_TIMEOUT);
throw new BranchRemoteException(BranchError.ERR_BRANCH_TASK_TIMEOUT, ex.getMessage());
}
}
// Unable to resolve host/Unknown host exception
catch (IOException ex) {
BranchLogger.v("Encountered exception while attempting network request: " + Log.getStackTraceString(ex));
if (retryNumber < prefHelper.getRetryCount()) {
try {
Thread.sleep(prefHelper.getRetryInterval());
Expand All @@ -262,15 +265,15 @@ private BranchResponse doRestfulPost(String url, JSONObject payload, int retryNu
return doRestfulPost(url, payload, retryNumber);
}
else {
throw new BranchRemoteException(BranchError.ERR_BRANCH_NO_CONNECTIVITY);
throw new BranchRemoteException(BranchError.ERR_BRANCH_NO_CONNECTIVITY, ex.getMessage());
}
} catch (Exception ex) {
BranchLogger.v("Exception: " + ex.getMessage());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
if (ex instanceof NetworkOnMainThreadException)
BranchLogger.v("Branch Error: Don't call our synchronous methods on the main thread!!!");
BranchLogger.v("Encountered exception while attempting network request: " + Log.getStackTraceString(ex));
if (ex instanceof NetworkOnMainThreadException) {
BranchLogger.v("Branch Error: Cannot make network request on main thread: " + Log.getStackTraceString(ex));
throw new BranchRemoteException((BranchError.ERR_NETWORK_ON_MAIN), ex.getMessage());
}
return new BranchResponse(null, 500);
throw new BranchRemoteException(BranchError.ERR_OTHER, ex.getMessage());
} finally {
if (connection != null) {
connection.disconnect();
Expand Down

0 comments on commit 91fc017

Please sign in to comment.