Skip to content

feat: Error tree#2663

Closed
RobinTail wants to merge 11 commits intomasterfrom
feat-error-tree
Closed

feat: Error tree#2663
RobinTail wants to merge 11 commits intomasterfrom
feat-error-tree

Conversation

@RobinTail
Copy link
Copy Markdown
Owner

@RobinTail RobinTail commented May 25, 2025

https://zod.dev/error-formatting#ztreeifyerror

This should make it easer to display errors in UI form by default.

Summary by CodeRabbit

  • New Features
    • Error responses for several endpoints now include an optional structured error tree, providing more detailed validation error information.
  • Documentation
    • Updated API documentation to describe the new structured error tree in error responses.
  • Tests
    • Switched input validation error response tests to use snapshot testing for improved maintainability.

@RobinTail RobinTail added the enhancement New feature or request label May 25, 2025
Comment thread example/example.documentation.yaml Outdated
@coveralls-official
Copy link
Copy Markdown

coveralls-official Bot commented May 25, 2025

Coverage Status

coverage: 100.0%. remained the same
when pulling 9cbe493 on feat-error-tree
into 34f1488 on master.

@RobinTail RobinTail added this to the v24 milestone May 25, 2025
@RobinTail RobinTail added refactoring The better way to achieve the same result prevention labels May 25, 2025
RobinTail added a commit that referenced this pull request May 25, 2025
@RobinTail RobinTail removed refactoring The better way to achieve the same result prevention labels May 25, 2025
@RobinTail RobinTail force-pushed the feat-error-tree branch 2 times, most recently from 1be1762 to a9903d1 Compare May 25, 2025 23:34
RobinTail added a commit that referenced this pull request May 26, 2025
Switching to zod core's `toDotPath()` in `getMessageFromError()`.

I'm not using `z.prettifyError()` because its prettiness to me is
questionable due to:
- icons/symbols
- new lines
- offsets 

In my opinion such formatting should be delegated to UI.
For that I'm planning #2663
.object({
status: z.literal("error"),
error: z.object({ message: z.string() }),
tree: errorTreeSchema.optional(),
Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

perhaps I should rather make a dedicated formResultHandler for that purpose

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 28, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

A recursive error tree type and its schema were introduced and integrated into error response types and OpenAPI schemas for several API endpoints. The result handler now includes a structured tree property in error responses for input validation errors. Related tests were updated to use snapshot assertions for error responses.

Changes

File(s) Change Summary
example/example.client.ts Added recursive error detail type Type2 and optional tree property to multiple negative response types.
example/example.documentation.yaml Updated OpenAPI error response schemas to include a tree property referencing new recursive schema Schema2.
express-zod-api/src/result-helpers.ts Added exported recursive Zod schema errorTreeSchema for structured error tree representation.
express-zod-api/src/result-handler.ts Extended error response schema and handler to include optional tree property for input validation errors.
express-zod-api/tests/endpoint.spec.ts Switched error response assertions from explicit values to snapshot testing for input validation failures.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant Validator
    participant ResultHandler

    Client->>API: Send request with input
    API->>Validator: Validate input
    Validator-->>API: Return validation error (if any)
    API->>ResultHandler: Handle error
    alt InputValidationError
        ResultHandler->>Validator: z.treeifyError(error.cause)
        ResultHandler-->>Client: Respond with error object (includes tree)
    else Other error
        ResultHandler-->>Client: Respond with error object (tree undefined)
    end
Loading

Poem

In the warren of code, a new tree has grown,
With branches of errors, now clearly shown.
Snapshots will capture each twist and each root,
While rabbits in docs find the details quite cute.
Recursive and neat, our errors now gleam—
Structured and clear, a developer’s dream!
🐇🌳


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

@RobinTail
Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 28, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

@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

♻️ Duplicate comments (4)
example/example.documentation.yaml (4)

239-240: Document optional tree in PATCH /v1/user/{id} 400 response


543-544: Document optional tree in POST /v1/avatar/upload 400 response


612-613: Document optional tree in POST /v1/avatar/raw 400 response


740-741: Document optional tree in POST /v1/forms/feedback 400 response

🧹 Nitpick comments (2)
example/example.documentation.yaml (2)

74-75: Document optional tree in GET /v1/user/retrieve 400 response
You’ve correctly added an optional tree property referencing Schema2. Since it’s not in the required array, consider updating the examples block to illustrate how the tree structure appears in practice. This will help API consumers understand and parse the new field.


766-787: Enhance recursive error tree schema (Schema2)
The new Schema2 models a recursive error tree nicely. A few optional refinements:

  1. Replace id: errorTreeSchema with $id to align with JSON Schema Draft 2020-12 in OpenAPI 3.1 (e.g. $id: "https://example.com/components/schemas/Schema2").
  2. Add description fields for the schema and each property (errors, items, properties) to clarify their roles.
  3. Review whether nested nodes need additionalProperties: false or more granular control.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c1d875b and 58c0d05.

⛔ Files ignored due to path filters (6)
  • example/__snapshots__/index.spec.ts.snap is excluded by !**/*.snap
  • express-zod-api/tests/__snapshots__/documentation.spec.ts.snap is excluded by !**/*.snap
  • express-zod-api/tests/__snapshots__/endpoint.spec.ts.snap is excluded by !**/*.snap
  • express-zod-api/tests/__snapshots__/integration.spec.ts.snap is excluded by !**/*.snap
  • express-zod-api/tests/__snapshots__/result-handler.spec.ts.snap is excluded by !**/*.snap
  • express-zod-api/tests/__snapshots__/system.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (5)
  • example/example.client.ts (6 hunks)
  • example/example.documentation.yaml (6 hunks)
  • express-zod-api/src/result-handler.ts (3 hunks)
  • express-zod-api/src/result-helpers.ts (1 hunks)
  • express-zod-api/tests/endpoint.spec.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
express-zod-api/src/result-handler.ts (3)
express-zod-api/src/result-helpers.ts (1)
  • errorTreeSchema (104-114)
express-zod-api/src/errors.ts (1)
  • InputValidationError (69-75)
express-zod-api/src/index.ts (1)
  • InputValidationError (26-26)
🔇 Additional comments (8)
express-zod-api/src/result-helpers.ts (1)

104-114: Excellent implementation of the recursive error tree schema!

The use of getters for items and properties is a clever solution to avoid circular reference issues during schema definition. The structure perfectly matches Zod's treeifyError output format, enabling proper typing for nested validation errors. The metadata ID ensures proper schema identification in OpenAPI generation.

express-zod-api/tests/endpoint.spec.ts (2)

566-566: Appropriate test strategy update for enhanced error responses.

Switching to snapshot testing makes sense here since the error responses now include the complex tree property with nested structures. This approach maintains test coverage while being more resilient to the detailed structure changes in error responses.


632-632: Consistent test approach for error response validation.

Good consistency in using snapshot testing for input validation error responses across different test scenarios.

express-zod-api/src/result-handler.ts (3)

10-10: Clean imports for error tree functionality.

Properly importing the required InputValidationError and errorTreeSchema for the new feature implementation.

Also applies to: 16-16


120-120: Well-designed schema extension.

Adding the tree property as optional maintains backward compatibility while enabling the new structured error functionality. The use of errorTreeSchema ensures type consistency across the application.


136-139: Excellent conditional error tree implementation.

The logic correctly:

  • Only adds the tree property for InputValidationError instances
  • Uses error.cause (which is a ZodError) with z.treeifyError()
  • Maintains clean separation between different error types
  • Provides structured validation error details when most beneficial

This implementation aligns perfectly with the PR objective of facilitating easier error display in UI forms.

example/example.client.ts (2)

6-10: Well-structured recursive error type definition.

The Type2 type perfectly mirrors the server-side errorTreeSchema structure:

  • errors array for validation messages
  • Optional items for array-level errors
  • Optional properties for object-level errors
  • Proper recursive self-references

This ensures type consistency between client and server for the error tree feature.


41-41: Consistent application of error tree types across endpoints.

The optional tree property has been appropriately added to all relevant negative response variants (HTTP 400 errors) that could contain input validation errors. This provides consistent error handling capabilities across different API endpoints while maintaining backward compatibility.

Also applies to: 102-102, 239-239, 269-269, 330-330

Base automatically changed from make-v24 to master May 28, 2025 13:03
@RobinTail RobinTail removed this from the v24 milestone May 28, 2025
@RobinTail RobinTail changed the title feat(v24): Error tree feat: Error tree Jun 13, 2025
@RobinTail
Copy link
Copy Markdown
Owner Author

should not overload the default RH

@RobinTail RobinTail closed this Sep 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant