Skip to content

Conversation

@shubham1g5
Copy link
Contributor

Product Description

Any network response codes we are not handling specifically crashes today but instead they should be failing with an error message and should allow user to retry the network request. Therefore I am failing them with UNKNOWN_ERROR instead.

Labels and Review

  • Do we need to enhance the manual QA test coverage ? If yes, the "QA Note" label is set correctly
  • Does the PR introduce any major changes worth communicating ? If yes, the "Release Note" label is set and a "Release Note" is specified in PR description.
  • Risk label is set correctly
  • The set of people pinged as reviewers is appropriate for the level of risk of the change

@shubham1g5 shubham1g5 changed the base branch from master to commcare_2.57 June 12, 2025 06:58
@shubham1g5 shubham1g5 added the skip-integration-tests Skip android tests. label Jun 12, 2025
@shubham1g5 shubham1g5 requested review from Jignesh-dimagi, OrangeAndGreen and pm-dimagi and removed request for Jignesh-dimagi June 12, 2025 06:59
@coderabbitai
Copy link

coderabbitai bot commented Jun 12, 2025

📝 Walkthrough

Walkthrough

The change updates the error handling logic in the processFailure method of the IApiCallback implementation within PersonalIdApiHandler.java. Specifically, when an unclassified HTTP failure occurs, the error code passed to the onFailure method is changed from INVALID_RESPONSE_ERROR to UNKNOWN_ERROR. The exception object containing the response information remains the same. No other modifications to control flow or error logic are present.

Possibly related PRs

  • More API error messages #3180: Adds the UNKNOWN_ERROR code and updates error message handling for it, which is directly related to the change in error code usage in PersonalIdApiHandler.

Suggested reviewers

  • OrangeAndGreen
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch correctErrorHandling
  • Post Copyable Unit Tests in Comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c8ca1db and be67280.

📒 Files selected for processing (1)
  • app/src/org/commcare/connect/network/PersonalIdApiHandler.java (1 hunks)

}
}
onFailure(PersonalIdApiErrorCodes.INVALID_RESPONSE_ERROR, new Exception(info.toString()));
onFailure(PersonalIdApiErrorCodes.UNKNOWN_ERROR, new Exception(info.toString()));
Copy link

@coderabbitai coderabbitai bot Jun 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Mismatch between error code and retry policy

The PR switches to UNKNOWN_ERROR for unclassified HTTP responses, but UNKNOWN_ERROR is not included in PersonalIdApiErrorCodes.shouldAllowRetry(). Therefore, these failures won’t be retryable despite the objective to allow retries on unhandled codes.
Please update the retry policy to include UNKNOWN_ERROR, or choose a retryable code.

Apply this diff to include UNKNOWN_ERROR in the retry check:

 public boolean shouldAllowRetry(){
-   return this == NETWORK_ERROR || this == TOKEN_UNAVAILABLE_ERROR
-           || this == SERVER_ERROR || this == RATE_LIMIT_EXCEEDED_ERROR;
+   return this == NETWORK_ERROR || this == TOKEN_UNAVAILABLE_ERROR
+           || this == SERVER_ERROR || this == RATE_LIMIT_EXCEEDED_ERROR
+           || this == UNKNOWN_ERROR;
 }
🤖 Prompt for AI Agents
In app/src/org/commcare/connect/network/PersonalIdApiHandler.java at line 103,
the error code UNKNOWN_ERROR is used for unclassified HTTP responses but is not
included in the retry policy method PersonalIdApiErrorCodes.shouldAllowRetry().
To fix this, update the shouldAllowRetry() method to include UNKNOWN_ERROR as a
retryable code so that these failures will be retried as intended.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Show the `shouldAllowRetry` method to verify if `UNKNOWN_ERROR` is now included.
rg -n "shouldAllowRetry" -A 4 -B 2 app/src/org/commcare/connect/network/PersonalIdApiHandler.java

Length of output: 359


@shubham1g5 great, I just checked the latest commit (c06189c…) and the shouldAllowRetry() method now contains UNKNOWN_ERROR, so unclassified HTTP responses will be retriable as intended:

public boolean shouldAllowRetry(){
    return this == NETWORK_ERROR
        || this == TOKEN_UNAVAILABLE_ERROR
        || this == SERVER_ERROR
        || this == UNKNOWN_ERROR;
}

With this change in place the retry behaviour now matches the goal of the PR.
Thanks for addressing the feedback so quickly!


🧬 Code Graph Analysis Results

Relevant snippets for app/src/org/commcare/connect/network/PersonalIdApiHandler.java


File: app/src/org/commcare/connect/network/parser/AddOrVerifyNameParser.java

Lines: 12-25

public class AddOrVerifyNameParser implements PersonalIdApiResponseParser {
    /**
     * Parses and sets values on the given PersonalIdSessionData instance.
     *
     * @param sessionData the instance to populate
     * @throws JSONException if a parsing error occurs
     */

    @Override
    public void parse(JSONObject json, PersonalIdSessionData sessionData) throws JSONException {
        sessionData.setAccountExists(json.optBoolean("account_exists", false));
        sessionData.setPhotoBase64(JsonExtensions.optStringSafe(json, "photo", null));
    }
}

File: app/src/org/commcare/connect/network/parser/CompleteProfileResponseParser.java

Lines: 14-27

public class CompleteProfileResponseParser implements PersonalIdApiResponseParser {
    /**
     * Parses and sets values on the given PersonalIdSessionData instance.
     *
     * @param sessionData the instance to populate
     * @throws JSONException if a parsing error occurs
     */
    @Override
    public void parse(JSONObject json, PersonalIdSessionData sessionData) throws JSONException {
        sessionData.setPersonalId(Objects.requireNonNull(JsonExtensions.optStringSafe(json, "username", null)));
        sessionData.setDbKey(Objects.requireNonNull(JsonExtensions.optStringSafe(json, "db_key", null)));
        sessionData.setOauthPassword(Objects.requireNonNull(JsonExtensions.optStringSafe(json, "password", null)));
    }
}

File: app/src/org/commcare/connect/network/parser/ConfirmBackupCodeResponseParser.java

Lines: 12-28

public class ConfirmBackupCodeResponseParser implements PersonalIdApiResponseParser{
    /**
     * Parses and sets values on the given PersonalIdSessionData instance.
     *
     * @param sessionData the instance to populate
     * @throws JSONException if a parsing error occurs
     */
    @Override
    public void parse(JSONObject json, PersonalIdSessionData sessionData) throws JSONException {
        sessionData.setPersonalId(JsonExtensions.optStringSafe(json, "username", null));
        sessionData.setDbKey(JsonExtensions.optStringSafe(json, "db_key", null));
        if (json.has("attempts_left")) {
            sessionData.setAttemptsLeft(json.getInt("attempts_left"));
        }
        sessionData.setOauthPassword(JsonExtensions.optStringSafe(json, "password", null));
    }
}

File: app/src/org/commcare/connect/network/parser/StartConfigurationResponseParser.java

Lines: 12-28

public class StartConfigurationResponseParser implements PersonalIdApiResponseParser {

    /**
     * Parses and sets values on the given PersonalIdSessionData instance.
     *
     * @param sessionData the instance to populate
     * @throws JSONException if a parsing error occurs
     */
    @Override
    public void parse(JSONObject json, PersonalIdSessionData sessionData) throws JSONException {
        sessionData.setRequiredLock(JsonExtensions.optStringSafe(json, "required_lock", null));
        sessionData.setDemoUser(json.optBoolean("demo_user", false));
        sessionData.setToken(JsonExtensions.optStringSafe(json, "token", null));
        sessionData.setSessionFailureCode(JsonExtensions.optStringSafe(json, "failure_code", null));
        sessionData.setSessionFailureSubcode(JsonExtensions.optStringSafe(json, "failure_subcode", null));
    }
}

File: app/src/org/commcare/connect/network/ApiPersonalId.java

Lines: 48-366 (summarized)

/**
 * Provides static methods to make network API calls related to Personal ID functionality.
 * Methods include:
 * - startConfiguration: starts configuration with integrity token and request hash.
 * - validateFirebaseIdToken: validates a Firebase ID token with the server.
 * - addOrVerifyName: sends a name to be added or verified.
 * - confirmBackupCode: confirms a backup code.
 * - setPhotoAndCompleteProfile: sets user photo and completes profile.
 *
 * Each method constructs appropriate HTTP requests using Retrofit ApiService,
 * handles authentication tokens, and uses a common callApi method to enqueue calls.
 *
 * callApi method:
 * - Shows a progress dialog.
 * - Enqueues the Retrofit call asynchronously.
 * - On success, passes InputStream of response body to callback.processSuccess.
 * - On failure, logs error and passes error stream or null to callback.processFailure.
 * - On network failure, logs and calls callback.processNetworkFailure.
 *
 * Error handling methods log network and HTTP errors.
 */
public class ApiPersonalId {
    // Constants for API versions and client IDs.

    // Various static methods for API calls, e.g.:
    public static void startConfiguration(Context context, Map<String, String> body, String integrityToken,
            String requestHash, IApiCallback callback) {
        ApiService apiService = ApiClient.getClientApi();
        Call<ResponseBody> call = apiService.startConfiguration(integrityToken, requestHash, body);
        callApi(context, call, callback);
    }

    public static void validateFirebaseIdToken(String token, Context context, String firebaseIdToken, IApiCallback callback) {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", firebaseIdToken);
        AuthInfo authInfo = new AuthInfo.TokenAuth(token);
        String tokenAuth = HttpUtils.getCredential(authInfo);
        Objects.requireNonNull(tokenAuth);
        ApiService apiService = ApiClient.getClientApi();
        Call<ResponseBody> call = apiService.validateFirebaseIdToken(tokenAuth, params);
        callApi(context, call, callback);
    }

    public static void addOrVerifyName(Context context, String name, String token, IApiCallback callback) {
        HashMap<String, String> params = new HashMap<>();
        params.put("name", name);

        AuthInfo authInfo = new AuthInfo.TokenAuth(token);
        String tokenAuth = HttpUtils.getCredential(authInfo);
        Objects.requireNonNull(tokenAuth);

        ApiService apiService = ApiClient.getClientApi();
        Call<ResponseBody> call = apiService.checkName(tokenAuth, params);
        callApi(context, call, callback);
    }

    public static void confirmBackupCode(Context context,
                                String backupCode, String token, IApiCallback callback) {

        HashMap<String, String> params = new HashMap<>();
        params.put("recovery_pin", backupCode);

        AuthInfo authInfo = new AuthInfo.TokenAuth(token);
        String tokenAuth = HttpUtils.getCredential(authInfo);

        ApiService apiService = ApiClient.getClientApi();
        Call<ResponseBody> call = apiService.confirmBackupCode(tokenAuth, params);
        callApi(context, call, callback);
    }

    public static void setPhotoAndCompleteProfile(Context context, String userName,
                                                  String photoAsBase64, String backupCode, String token, IApiCallback callback) {
        Objects.requireNonNull(photoAsBase64);
        Objects.requireNonNull(userName);
        AuthInfo authInfo = new AuthInfo.TokenAuth(token);
        String tokenAuth = HttpUtils.getCredential(authInfo);
        Objects.requireNonNull(tokenAuth);

        HashMap<String, String> params = new HashMap<>();
        params.put("photo", photoAsBase64);
        params.put("name", userName);
        params.put("recovery_pin", backupCode);

        ApiService apiService = ApiClient.getClientApi();
        Call<ResponseBody> call = apiService.completeProfile(tokenAuth, params);
        callApi(context, call, callback);
    }

    // Internal helper methods for logging and error handling.
}

These snippets provide context on:

  • How the PersonalIdApiHandler uses various parsers to parse API responses into PersonalIdSessionData.
  • The API calls made via ApiPersonalId static methods, which correspond to the calls made in PersonalIdApiHandler.
  • The callback mechanism and error handling used in the network calls.
  • The parsing logic for different API responses.

This context is directly relevant to understanding the implementation and behavior of PersonalIdApiHandler.java.

@shubham1g5 shubham1g5 merged commit 48f725a into commcare_2.57 Jun 12, 2025
1 of 2 checks passed
@shubham1g5 shubham1g5 deleted the correctErrorHandling branch June 12, 2025 07:41
@coderabbitai coderabbitai bot mentioned this pull request Oct 14, 2025
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-integration-tests Skip android tests.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants