Skip to content

Fix issue #2858: Improve error messages in field validation functions #2961

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

lacostenycoder
Copy link

High Level Overview of Change

  • Improved error messages in field validation functions to include expected and actual types
  • Added tests to verify the improved error messages work correctly
  • Fixed line endings in test files

Context of Change

The validation functions in the XRPL.js library previously provided generic error messages when field validation failed. This PR improves these error messages by including both the expected type and the actual type received, making it easier for developers to debug issues with their transactions.

The changes specifically enhance the validateRequiredField and validateOptionalField functions in the transaction validation system to provide more descriptive error messages, and adds comprehensive test coverage for these improved messages.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Refactor (non-breaking change that only restructures code)
  • Tests (You added tests for code that already exists, or your new feature included in this PR)
  • Documentation Updates
  • Release

Did you update HISTORY.md?

  • Yes
  • No, this change does not impact library users

Test Plan

The changes have been verified by:

  1. Adding unit tests in packages/xrpl/test/models/transactions/common.test.ts that verify the improved error messages
  2. Testing that validation functions properly include expected and actual types in error messages
  3. Ensuring backward compatibility with existing code by maintaining the same error types and general message format

The tests specifically verify:

  • Error messages now include both expected and actual types
  • Validation still works correctly for valid values
  • Validation still produces proper errors for missing fields
  • The optional field validation still behaves as expected

Copy link

coderabbitai bot commented Apr 9, 2025

Walkthrough

This pull request modifies the validation behavior in the XRPL transaction model. The changes introduce an additional optional parameter, expectedType, to both the validateRequiredField and validateOptionalField functions in the common module. This update enhances the clarity of error messages by reporting the expected versus received type. Additionally, the related transaction field validations in validateBaseTransaction are updated, and corresponding unit tests have been added to cover various scenarios for both functions.

Changes

File(s) Change Summary
packages/xrpl/src/.../transactions/common.ts Updated validateRequiredField and validateOptionalField to include an optional expectedType parameter; error messages now report expected and actual types; updated calls in validateBaseTransaction.
packages/xrpl/test/.../transactions/common.test.ts Added a new test suite for the validation functions, covering various scenarios including type mismatches and missing fields.
packages/xrpl/test/.eslintrc.js Introduced a new ESLint configuration file that disables the requirement for JSDoc comments in the codebase.

Possibly related issues

Suggested reviewers

  • mvadari
  • achowdhry-ripple
  • ckeshava
  • khancode

Poem

I hopped through lines of code so neat,
Adding types to every beat.
Error messages now sing their song,
Telling what went right or wrong.
In fields required, a clear type view,
A bunny's hop brings bug-fixing through!
🐇✨ Happy coding, on we go!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • 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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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 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: 0

🧹 Nitpick comments (4)
packages/xrpl/test/models/transactions/common.test.ts (2)

1-2: Reorder imports as per project convention.

The static analysis is flagging that imports should be ordered alphabetically. Following the project's import ordering convention improves consistency across the codebase.

-import { validateRequiredField, validateOptionalField } from '../../../src/models/transactions/common'
-import { ValidationError } from '../../../src/errors'
+import { ValidationError } from '../../../src/errors'
+import { validateRequiredField, validateOptionalField } from '../../../src/models/transactions/common'
🧰 Tools
🪛 ESLint

[error] 1-1: Replace ·validateRequiredField,·validateOptionalField· with ⏎··validateRequiredField,⏎··validateOptionalField,⏎

(prettier/prettier)


[error] 2-2: ../../../src/errors import should occur before import of ../../../src/models/transactions/common

(import/order)


13-14: Format multi-line function calls for better readability.

The static analysis tool is suggesting to break the function call into multiple lines for better readability.

-    expect(() =>
-      validateRequiredField(txMock, 'amount', (val) => typeof val === 'string', 'string')
-    ).toThrow(new ValidationError('Payment: invalid field amount: expected string, received number'))
+    expect(() =>
+      validateRequiredField(
+        txMock,
+        'amount',
+        (val) => typeof val === 'string',
+        'string',
+      ),
+    ).toThrow(
+      new ValidationError(
+        'Payment: invalid field amount: expected string, received number',
+      ),
+    )
🧰 Tools
🪛 ESLint

[error] 13-13: Replace txMock,·'amount',·(val)·=>·typeof·val·===·'string',·'string') with ⏎········txMock,⏎········'amount',⏎········(val)·=>·typeof·val·===·'string',⏎········'string',⏎······),

(prettier/prettier)


[error] 14-14: Replace new·ValidationError('Payment:·invalid·field·amount:·expected·string,·received·number') with ⏎······new·ValidationError(⏎········'Payment:·invalid·field·amount:·expected·string,·received·number',⏎······),⏎····

(prettier/prettier)

packages/xrpl/src/models/transactions/common.ts (2)

237-237: Fix line formatting for better readability.

The static analysis tool is suggesting to break the line for better readability.

-      `${tx.TransactionType}: invalid field ${paramName}${expectedType ? `: expected ${expectedType}, received ${actualType}` : ''}`,
+      `${tx.TransactionType}: invalid field ${paramName}${
+        expectedType ? `: expected ${expectedType}, received ${actualType}` : ''
+      }`,
🧰 Tools
🪛 ESLint

[error] 237-237: Replace expectedType·?·:·expected·${expectedType},·received·${actualType}·:·'' with ⏎········expectedType·?·:·expected·${expectedType},·received·${actualType}·:·''⏎······

(prettier/prettier)


260-260: Fix line formatting to match the other validation function.

For consistency with the similar fix in validateRequiredField.

-      `${tx.TransactionType}: invalid field ${paramName}${expectedType ? `: expected ${expectedType}, received ${actualType}` : ''}`,
+      `${tx.TransactionType}: invalid field ${paramName}${
+        expectedType ? `: expected ${expectedType}, received ${actualType}` : ''
+      }`,
🧰 Tools
🪛 ESLint

[error] 260-260: Replace expectedType·?·:·expected·${expectedType},·received·${actualType}·:·'' with ⏎········expectedType·?·:·expected·${expectedType},·received·${actualType}·:·''⏎······

(prettier/prettier)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between effe757 and 2bbbd68.

📒 Files selected for processing (2)
  • packages/xrpl/src/models/transactions/common.ts (5 hunks)
  • packages/xrpl/test/models/transactions/common.test.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
packages/xrpl/test/models/transactions/common.test.ts (1)
Learnt from: ckeshava
PR: XRPLF/xrpl.js#2874
File: packages/xrpl/src/models/transactions/common.ts:0-0
Timestamp: 2025-04-07T16:40:26.679Z
Learning: Test libraries like chai should not be used in source code. Use existing validation functions where available, or implement custom validation using ValidationError for runtime checks.
packages/xrpl/src/models/transactions/common.ts (1)
Learnt from: achowdhry-ripple
PR: XRPLF/xrpl.js#2661
File: packages/xrpl/src/models/transactions/MPTokenIssuanceCreate.ts:69-102
Timestamp: 2025-04-07T16:40:26.680Z
Learning: When adding validation in `validate*` functions in `packages/xrpl/src/models/transactions/`, utilize existing helper functions (e.g., `validateOptionalField`, `validateType`, `isNumber`, `isInteger`) for type checking and validation where appropriate.
🪛 ESLint
packages/xrpl/test/models/transactions/common.test.ts

[error] 1-1: Replace ·validateRequiredField,·validateOptionalField· with ⏎··validateRequiredField,⏎··validateOptionalField,⏎

(prettier/prettier)


[error] 2-2: ../../../src/errors import should occur before import of ../../../src/models/transactions/common

(import/order)


[error] 13-13: Replace txMock,·'amount',·(val)·=>·typeof·val·===·'string',·'string') with ⏎········txMock,⏎········'amount',⏎········(val)·=>·typeof·val·===·'string',⏎········'string',⏎······),

(prettier/prettier)


[error] 14-14: Replace new·ValidationError('Payment:·invalid·field·amount:·expected·string,·received·number') with ⏎······new·ValidationError(⏎········'Payment:·invalid·field·amount:·expected·string,·received·number',⏎······),⏎····

(prettier/prettier)


[error] 19-19: Replace txMock,·'account',·(val)·=>·typeof·val·===·'string',·'string') with ⏎········txMock,⏎········'account',⏎········(val)·=>·typeof·val·===·'string',⏎········'string',⏎······),

(prettier/prettier)


[error] 25-25: Insert ,

(prettier/prettier)


[error] 31-31: Replace txMock,·'nonExistentField',·(val)·=>·typeof·val·===·'string') with ⏎········txMock,⏎········'nonExistentField',⏎········(val)·=>·typeof·val·===·'string',⏎······),

(prettier/prettier)


[error] 48-48: Replace txNoMemo,·'memo',·(val)·=>·typeof·val·===·'string',·'string') with ⏎········txNoMemo,⏎········'memo',⏎········(val)·=>·typeof·val·===·'string',⏎········'string',⏎······),

(prettier/prettier)


[error] 54-54: Replace txMock,·'memo',·(val)·=>·typeof·val·===·'string',·'string') with ⏎········txMock,⏎········'memo',⏎········(val)·=>·typeof·val·===·'string',⏎········'string',⏎······),

(prettier/prettier)


[error] 55-55: Replace new·ValidationError('Payment:·invalid·field·memo:·expected·string,·received·number') with ⏎······new·ValidationError(⏎········'Payment:·invalid·field·memo:·expected·string,·received·number',⏎······),⏎····

(prettier/prettier)

packages/xrpl/src/models/transactions/common.ts

[error] 237-237: Replace expectedType·?·:·expected·${expectedType},·received·${actualType}·:·'' with ⏎········expectedType·?·:·expected·${expectedType},·received·${actualType}·:·''⏎······

(prettier/prettier)


[error] 260-260: Replace expectedType·?·:·expected·${expectedType},·received·${actualType}·:·'' with ⏎········expectedType·?·:·expected·${expectedType},·received·${actualType}·:·''⏎······

(prettier/prettier)

🔇 Additional comments (6)
packages/xrpl/test/models/transactions/common.test.ts (2)

4-34: Great test coverage for validateRequiredField!

The tests thoroughly cover all important scenarios for the enhanced error messages:

  1. When validation fails with expected and received types
  2. When validation succeeds
  3. When expectedType is not provided
  4. When a field is missing entirely

This ensures the validation function behaves correctly across different use cases.

🧰 Tools
🪛 ESLint

[error] 13-13: Replace txMock,·'amount',·(val)·=>·typeof·val·===·'string',·'string') with ⏎········txMock,⏎········'amount',⏎········(val)·=>·typeof·val·===·'string',⏎········'string',⏎······),

(prettier/prettier)


[error] 14-14: Replace new·ValidationError('Payment:·invalid·field·amount:·expected·string,·received·number') with ⏎······new·ValidationError(⏎········'Payment:·invalid·field·amount:·expected·string,·received·number',⏎······),⏎····

(prettier/prettier)


[error] 19-19: Replace txMock,·'account',·(val)·=>·typeof·val·===·'string',·'string') with ⏎········txMock,⏎········'account',⏎········(val)·=>·typeof·val·===·'string',⏎········'string',⏎······),

(prettier/prettier)


[error] 25-25: Insert ,

(prettier/prettier)


[error] 31-31: Replace txMock,·'nonExistentField',·(val)·=>·typeof·val·===·'string') with ⏎········txMock,⏎········'nonExistentField',⏎········(val)·=>·typeof·val·===·'string',⏎······),

(prettier/prettier)


36-57: Good test coverage for validateOptionalField.

The tests verify both core behaviors of the optional field validation:

  1. Skipping validation when the field is undefined
  2. Performing validation when the field is present but invalid

This ensures the enhanced error message functionality works correctly for optional fields too.

🧰 Tools
🪛 ESLint

[error] 48-48: Replace txNoMemo,·'memo',·(val)·=>·typeof·val·===·'string',·'string') with ⏎········txNoMemo,⏎········'memo',⏎········(val)·=>·typeof·val·===·'string',⏎········'string',⏎······),

(prettier/prettier)


[error] 54-54: Replace txMock,·'memo',·(val)·=>·typeof·val·===·'string',·'string') with ⏎········txMock,⏎········'memo',⏎········(val)·=>·typeof·val·===·'string',⏎········'string',⏎······),

(prettier/prettier)


[error] 55-55: Replace new·ValidationError('Payment:·invalid·field·memo:·expected·string,·received·number') with ⏎······new·ValidationError(⏎········'Payment:·invalid·field·memo:·expected·string,·received·number',⏎······),⏎····

(prettier/prettier)

packages/xrpl/src/models/transactions/common.ts (4)

219-226: Excellent addition of expectedType parameter!

The optional expectedType parameter is a valuable enhancement that will significantly improve the developer experience by providing more informative error messages. The JSDoc comments have been appropriately updated to document this new parameter.


234-238: Great enhancement to error messages!

This change significantly improves the error messages by including both the expected and actual types when validation fails. The code correctly handles the special case for null values and properly formats the message based on whether expectedType is provided.

🧰 Tools
🪛 ESLint

[error] 237-237: Replace expectedType·?·:·expected·${expectedType},·received·${actualType}·:·'' with ⏎········expectedType·?·:·expected·${expectedType},·received·${actualType}·:·''⏎······

(prettier/prettier)


257-261: Consistent implementation in validateOptionalField!

The error message enhancement is consistently implemented in both validation functions, which maintains code symmetry and ensures users get the same helpful error format regardless of which validation method is used.

🧰 Tools
🪛 ESLint

[error] 260-260: Replace expectedType·?·:·expected·${expectedType},·received·${actualType}·:·'' with ⏎········expectedType·?·:·expected·${expectedType},·received·${actualType}·:·''⏎······

(prettier/prettier)


365-399: Great update to validateBaseTransaction!

The function calls to validateRequiredField and validateOptionalField have been consistently updated to include the type information, which ensures users get helpful error messages for all validation failures in the base transaction fields.

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 (2)
packages/xrpl/src/models/transactions/common.ts (2)

220-224: Consider adding examples to the documentation

While the parameter documentation is clear, it might be helpful to add examples of the error messages with and without the expectedType parameter to help developers understand how to use these functions effectively.

 * @param checkValidity - The function to use to check the type.
 * @param expectedType - Optional. The expected type for more specific error messages.
+ *                      Example: With expectedType='string': "invalid field Account: expected string, received number"
+ *                      Example: Without expectedType: "invalid field Account"
 * @throws When the field is missing or invalid.

Also applies to: 251-255


224-229: Consider leveraging existing domain knowledge for expected type

The current implementation requires developers to manually specify the expected type as a string, which could lead to inconsistencies if the string doesn't match the actual type expected by the validation function.

You could consider a more type-safe approach by deriving the expected type from the checkValidity function's parameter type or return type constraints, potentially using TypeScript's type system to ensure consistency.

Also applies to: 255-260

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a53b0b6 and 8191d77.

📒 Files selected for processing (1)
  • packages/xrpl/src/models/transactions/common.ts (5 hunks)
🧰 Additional context used
🧠 Learnings (1)
packages/xrpl/src/models/transactions/common.ts (1)
Learnt from: achowdhry-ripple
PR: XRPLF/xrpl.js#2661
File: packages/xrpl/src/models/transactions/MPTokenIssuanceCreate.ts:69-102
Timestamp: 2025-04-09T22:09:21.852Z
Learning: When adding validation in `validate*` functions in `packages/xrpl/src/models/transactions/`, utilize existing helper functions (e.g., `validateOptionalField`, `validateType`, `isNumber`, `isInteger`) for type checking and validation where appropriate.
🔇 Additional comments (4)
packages/xrpl/src/models/transactions/common.ts (4)

213-214: Well-documented ESLint exceptions for improved error messages

The ESLint disable/enable comments are clearly documented with rationale for both the max-params exception (to allow the new parameter) and the template-expressions exception (for including type information in errors).

Also applies to: 270-271


221-222: Good improvement to error reporting in validateRequiredField

The addition of the optional expectedType parameter and enhanced error message formatting will make debugging validation issues much easier for developers. The implementation correctly handles null values separately from undefined and captures the actual type of the invalid field.

Also applies to: 224-229, 236-242


252-253: Good improvement to error reporting in validateOptionalField

Similar to the changes in validateRequiredField, this update adds better type reporting to optional field validation errors. The implementation is consistent with the required field validation function and maintains backward compatibility by making the parameter optional.

Also applies to: 255-260, 261-267


373-407: Comprehensive update to all validation calls

All calls to the validation functions within validateBaseTransaction have been properly updated to include the expected type information, ensuring consistent error reporting throughout the validation process.

@mvadari
Copy link
Collaborator

mvadari commented Apr 10, 2025

I prefer the solution in #2895, since that doesn't involve as much duplication in the function when writing it.

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.

2 participants