Skip to content

Implement nested error message handling for schema validation #13045

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 9, 2025

Conversation

Jithmi004
Copy link
Contributor

Purpose

The schema validator in the apimgt.gateway no longer returns the full error message to the user. Only the first error in the validation report is sent. This needs to be fixed.

Implementation Details

A function getErrorMessage() is implemented where it recursively checks whether the ValidationReport.Message has nested messages and get the concatenated message as the result. This fix has been added to both the handleRequest and handleResponse flows.

Related To

wso2/api-manager#3585

Copy link

coderabbitai bot commented Mar 7, 2025

📝 Walkthrough
## Walkthrough

The code has been updated in the SchemaValidator class to improve error message handling during schema validation. A new private method, `getErrorMessage`, has been introduced to recursively construct detailed error messages from nested validation errors. The updated logic now cleans up the final message output by removing the trailing comma and space, ensuring more structured error information in both request and response handling.

## Changes

| File(s)                                  | Change Summary                                                                                                                                          |
|------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|
| components/apimgt/.../SchemaValidator.java | Added a private method `getErrorMessage` to recursively accumulate nested error messages. Updated `handleRequest` and `handleResponse` to use the new method and remove the trailing comma and space from error messages. |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant Handler as handleRequest/handleResponse
    participant Validator as SchemaValidator
    participant Msg as ValidationReport.Message
    Handler->>Validator: Invoke getErrorMessage(topLevelMessage)
    Validator->>Msg: Check for nested errors
    alt Nested errors exist
        Validator->>Validator: Recursively call getErrorMessage(nestedMessage)
    end
    Validator->>Validator: Construct comprehensive error message
    Validator->>Validator: Remove trailing comma and space
    Validator->>Handler: Return formatted error message

Suggested reviewers

  • tgtshanika
  • chamilaadhi
  • tharindu1st
  • Arshardh
  • AnuGayan

</details>

<!-- walkthrough_end -->

<!-- announcements_start -->

> [!TIP]
> <details>
> <summary>⚡️ Faster reviews with caching</summary>
> 
> - CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure `Review - Disable Cache` at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the `Data Retention` setting under your Organization Settings.
> 
> Enjoy the performance boost—your workflow just got faster.
> 
> </details>

<!-- announcements_end -->
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+Ats2bgFyQAOFk+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEYDEZyAAUASpETZWaCrKNwSPbABsvkCiQBHbGlcSHFcLzpIACIASWZuSLYMUPJEGnpKCnw+NkRENFJIWExaL3gMIkgAMxz7BlgSZjRICTRy2mp4fAxoyAB3NGQHAWZ1DMg5SGxESkgAKXVYMYAGFYAWdAx6VHglFPhq+CihyAxHATmARgBmDYBWDRhGzwpufFn+arCEZFsUZAEdC0Wj+fJbAEODwVH4eRANJotNodah1fpLGG4F5objwZhETREagkQayAA0A0a/n4GC88ixHiOFHSkCydTyBSK1WyzFhrXaey6PT8JHeFFCqH8uGwFHI9CBDOmswoTzgqHKY1wQqw5AY0kQ6mJyBaRwAHmF8KyMA5qVjqErKMh/HrJB4mAl/I1ra7WRRsnwKrUKM1xD0NG5LWD8F4pD9dvlghTFXjEk12NqUClsrRsHrjWcSTVsBgxN0sAx2pF6AADUi4ACifpyAFl9YUSAAKACU1dVvyLJdDWFQSgNRDlFpFDBlBqkdMYjQYAGsanU0hMOe3kOisZiXtWAGoCzpDmyinKaVv5dvVrb0Jgl4kYYmw3kVIEtA2VSIU928EherOHhsrkbakH2jLwOaJQyCQZDoNwiTHPKloCPgWJ8iU2yRGeQQhHexSlDh0jvNajJePg/SIBSZA2hUVR2qEMyOlOJA+koWrwFWNRwbQAhoMuNL8iiQ6+v6iDhgYACCILqGWlbknGfx2JKJBeMSKEQiQppIOIlSQsEkC0Pg07JBMe4eAA6gAygA8gATJ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Fwas682g0EgNZCJ+k6yNn9EY0gHZr4yIwGeMUl4RHwJ7FlOZ4JqyX0RK81EFAz5YGrC7cgKR3ae3Jr7f22dA4ExDnCwkxJo6x3jn/ZOqc0Dp0zgHXOhN85opRhi0u5ciKOmrtOGqddEZAqbuDPybc8XVi7j3AwDMDBKytGojWXNta8yiPzdgXAqBGwcKPeQqDLYyzUDbBW9teVMwUKwdQAB9PYiBNX+GaiSOgmr0jOFCDyvlNxVE3BuAANhtTcAAnCsAA7PceyKwSAOuqPxNANr7LVA2NUANJABDOpWAIbJII6AOrtg7Pl/MtU6r1SQA1/QjUs1jUAA=== -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details open="true">
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

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.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=wso2/carbon-apimgt&utm_content=13045):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
  - `I pushed a fix in commit <commit_id>, please review it.`
  - `Generate unit testing code for this file.`
  - `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 generate unit testing code for this file.`
  -	`@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 generate unit testing code.`
  - `@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](https://www.coderabbit.ai/contact-us/support) 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](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR.
- `@coderabbitai generate sequence diagram` to generate a sequence diagram of the changes in 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.

### Documentation and Community

- Visit our [Documentation](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

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: 0

🧹 Nitpick comments (1)
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/SchemaValidator.java (1)

122-132: Well-implemented recursive error message concatenation.

The getErrorMessage method elegantly handles nested validation errors through recursion. The implementation correctly:

  1. Returns the base message when no nested messages exist
  2. Recursively processes all nested messages when present
  3. Properly formats the combined message with appropriate separators

This addresses the original issue where only the first error message was being returned to users, providing a much better debugging experience.

Consider adding a safeguard against extremely deep recursion (though unlikely in practice) to prevent potential stack overflow:

 private String getErrorMessage(ValidationReport.Message message){
+    return getErrorMessage(message, 0);
+}
+
+private String getErrorMessage(ValidationReport.Message message, int depth){
+    // Prevent extremely deep recursion (adjust max depth as needed)
+    if (depth > 100) {
+        return message.getMessage() + " [max depth reached]";
+    }
     if(message.getNestedMessages().isEmpty()){
         return message.getMessage();
     }
     StringBuilder combinedMessages = new StringBuilder();
     combinedMessages.append(message.getMessage());
     for (ValidationReport.Message nestedMessage : message.getNestedMessages()) {
-        combinedMessages.append(", ").append(getErrorMessage(nestedMessage));
+        combinedMessages.append(", ").append(getErrorMessage(nestedMessage, depth + 1));
     }
     return combinedMessages.toString().trim();
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5ee9d1e and 15a0833.

📒 Files selected for processing (1)
  • components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/SchemaValidator.java (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-product (4, group4)
  • GitHub Check: build-product (2, group2)
  • GitHub Check: run-benchmark-test
  • GitHub Check: build-carbon
  • GitHub Check: build-product (1, group1)
  • GitHub Check: build-product (3, group3)
🔇 Additional comments (2)
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/SchemaValidator.java (2)

81-86: Improved error message handling in request validation.

The change now properly concatenates all error messages including nested ones, providing more comprehensive feedback to API users. The cleanup of trailing commas and spaces makes the error messages more readable.


108-113: Consistent implementation of error message handling in response validation.

Good to see the same error message handling approach applied to both request and response validation paths, ensuring consistency in the error reporting mechanism.

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: 0

🧹 Nitpick comments (1)
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/SchemaValidator.java (1)

122-132: Well-implemented recursive method for handling nested messages

The getErrorMessage method elegantly handles the recursion needed to collect all nested validation messages. The base case and recursive case are properly handled, and the implementation is clean and efficient.

Consider a small optimization to avoid code duplication in both handleRequest and handleResponse:

 private String getErrorMessage(ValidationReport.Message message) {
     if (message.getNestedMessages().isEmpty()) {
         return message.getMessage();
     }
     StringBuilder combinedMessages = new StringBuilder();
     combinedMessages.append(message.getMessage());
     for (ValidationReport.Message nestedMessage : message.getNestedMessages()) {
         combinedMessages.append(", ").append(getErrorMessage(nestedMessage));
     }
     return combinedMessages.toString().trim();
 }

+/**
+ * Helper method to build a complete error message string from validation report messages.
+ *
+ * @param validationReport The validation report containing messages
+ * @return A formatted string with all error messages
+ */
+private String buildErrorMessageFromReport(ValidationReport validationReport) {
+    StringBuilder finalMessage = new StringBuilder();
+    for (ValidationReport.Message message : validationReport.getMessages()) {
+        finalMessage.append(getErrorMessage(message)).append(", ");
+    }
+    // Remove the last comma and space, if present
+    if (finalMessage.length() > 0) {
+        finalMessage.setLength(finalMessage.length() - 2);
+    }
+    return finalMessage.toString();
+}

This would allow you to replace the duplicated blocks in both handlers with a single method call:

String finalMessage = buildErrorMessageFromReport(validationReport);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c1d874a and 3ad3366.

📒 Files selected for processing (1)
  • components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/SchemaValidator.java (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-product (4, group4)
  • GitHub Check: build-product (3, group3)
  • GitHub Check: run-benchmark-test
  • GitHub Check: build-product (1, group1)
  • GitHub Check: build-carbon
  • GitHub Check: build-product (2, group2)
🔇 Additional comments (2)
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/SchemaValidator.java (2)

81-86: Good enhancement to include nested error messages!

The implementation now properly collects all validation errors, including nested ones, and presents them in a cleaner format by removing the trailing comma and space.


108-113: Same enhancement applied to response handling

The implementation correctly applies the same nested error message handling to the response validation flow, ensuring consistent behavior.

@npamudika npamudika merged commit b7ea7c9 into wso2:master May 9, 2025
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants