Skip to content

Conversation

@lauslim12
Copy link
Contributor

@lauslim12 lauslim12 commented Mar 4, 2025

Description

Hi there, thank you for making this library! It's very useful to generate OpenAPI schemas from Next.js's API route.

I noticed one thing that seems to be missing. Let's say for this code (in app/api/[symbol]):

import defineRoute from "@omer-x/next-openapi-route-handler";
import { z } from "zod";

export const { GET } = defineRoute({
	operationId: "getSymbol",
	method: "GET",
	summary: "Get a symbol",
	description: "Returns an object with the symbol as one of its properties.",
	tags: ["symbol"],
	pathParams: z.object({ symbol: z.enum(["QQQ", "SPY", "FXI"]) }),
	action: ({ pathParams }) => {
		return Response.json({ ticker: pathParams.symbol }, { status: 200 });
	},
	responses: {
		200: { description: "OK", content: z.object({ ticker: z.string() }) },
		422: { description: "Invalid parameters", content: z.array(z.string()) },
		500: { description: "Internal server error", content: "string" },
	},
	handleErrors: (errorType, issues) => {
		// Sample logging. Check this out in the output.
		console.log(errorType, issues);

		if (errorType === "PARSE_PATH_PARAMS") {
			// FIXME: `issues` does not have Zod issue, even though `PARSE_PATH_PARAMS` should have
			// Zod issues since it's validated by it.
			return Response.json(
				issues?.map((value) => value.path.toString()),
				{ status: 422 },
			);
		}

		return new Response("Internal server error", { status: 500 });
	},
});

This is the response, which I don't think is correct. issues should not be undefined since from the code above, pathParams are validated by the Zod schema.

[
  {
    received: 'BBRI.JK',
    code: 'invalid_enum_value',
    options: [ 'QQQ', 'SPY', 'FXI' ],
    path: [ 'symbol' ],
    message: "Invalid enum value. Expected 'QQQ' | 'SPY' | 'FXI', received 'BBRI.JK'"
  }
]
PARSE_PATH_PARAMS undefined // <- this should not be the case!
 ⨯ TypeError: Value is not JSON serializable
    at Object.handleErrors (app/api/[symbol]/route.ts:26:19)
  24 | 			// FIXME: `issues` does not have Zod issue, even though `PARSE_PATH_PARAMS` should have
  25 | 			// Zod issues since it's validated by it.
> 26 | 			return Response.json(
     | 			               ^
  27 | 				issues?.map((value) => value.path.toString()),
  28 | 				{ status: 422 },
  29 | 			);
 ⨯ TypeError: Value is not JSON serializable
    at Object.handleErrors (app/api/[symbol]/route.ts:26:19)
  24 | 			// FIXME: `issues` does not have Zod issue, even though `PARSE_PATH_PARAMS` should have
  25 | 			// Zod issues since it's validated by it.
> 26 | 			return Response.json(
     | 			               ^
  27 | 				issues?.map((value) => value.path.toString()),
  28 | 				{ status: 422 },
  29 | 			);
 GET /api/BBRI.JK 500 in 1568ms

Expected Behavior

I think issues should not be undefined. I noticed that for PARSE_PATH_PARAMS, we didn't put the ZodError as part of the cause. So, this PR should fix it.

Future

In the future, would be nice to strategically structure the code in such a way that if we get one of these error types, issues should never be undefined since these validations will always have to pass through the Zod schema, so ZodError shall always be there.

  • PARSE_FORM_DATA
  • PARSE_REQUEST_BODY
  • PARSE_SEARCH_PARAMS
  • PARSE_PATH_PARAMS

Thank you!

Summary by CodeRabbit

  • Bug Fixes
    • Improved error messaging during parsing errors by including additional context. This update provides clearer diagnostic information when issues occur, aiding troubleshooting without altering the public functionality.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 4, 2025

Walkthrough

The changes update the error handling in the parsePathParams function within the src/core/path-params.ts file. Instead of throwing a simple Error with the message "PARSE_PATH_PARAMS", the function now attaches additional context by including an options object with a cause property. This property contains issues extracted from the caught ZodError, thereby providing more details about the parsing failure.

Changes

File Change Summary
src/core/path-params.ts Updated error handling in parsePathParams to throw an error with a cause property containing issues from ZodError.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant PP as parsePathParams
    participant ZO as ZodError
    Caller->>PP: call parsePathParams(params)
    PP->>PP: attempt to parse parameters
    alt Parsing fails
        PP->>ZO: capture issues from ZodError
        PP->>Caller: throw Error("PARSE_PATH_PARAMS", {cause: issues})
    else Parsing successful
        PP->>Caller: return parsed parameters
    end
Loading

Possibly related PRs

  • [FEATURE] Custom Error Handler #6: Enhances error handling in parsing functions by adding a cause property to errors, aligning with the modifications in parsePathParams.

Poem

I'm a rabbit hopping through code,
Where errors now have a lighter load.
With a cause attached to every issue that flies,
Debugging's a breeze under open skies.
Hoppy coding, from my burrow with high vibes! 🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1d02b74 and f204cec.

📒 Files selected for processing (1)
  • src/core/path-params.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/core/path-params.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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
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

🧹 Nitpick comments (1)
src/core/path-params.ts (1)

14-14: Excellent improvement to error propagation!

This change properly propagates the Zod validation issues through the Error's cause property, which addresses the PR objective of ensuring that issues are available when handling PARSE_PATH_PARAMS errors.

Consider adding a null/type check before accessing issues to make the code more robust:

- throw new Error("PARSE_PATH_PARAMS", { cause: (error as ZodError).issues });
+ throw new Error("PARSE_PATH_PARAMS", { 
+   cause: error instanceof Error && 'issues' in error ? error.issues : error 
+ });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b32acda and 1d02b74.

📒 Files selected for processing (1)
  • src/core/path-params.ts (1 hunks)
🔇 Additional comments (2)
src/core/path-params.ts (2)

2-2: Type import looks good.

The ZodError import is correctly declared and is being used in the error handling logic.


7-15:

❓ Verification inconclusive

Verify error handling consistency across the codebase.

This change looks good for the parsePathParams function, but you might want to ensure similar error handling is applied consistently across other parsing functions in the library.


🏁 Script executed:

#!/bin/bash
# Description: Check other parsing functions to verify if they use similar error handling patterns.

# Look for other functions that might need similar error handling
rg -A 2 "throw new Error\(\"PARSE_" --type ts

# Check if there are other usages of ZodError in the codebase that might need attention
rg "as ZodError" --type ts

Length of output: 1563


Action: Verify uniform error handling across parsing functions

The error handling in src/core/path-params.ts looks solid and aligns with how most parsing functions handle errors. However, our search revealed a potential inconsistency in src/core/body.ts for the "PARSE_REQUEST_BODY" error: one instance throws an error using result.error?.issues while another uses (error as ZodError).issues. Please review this discrepancy to determine if it’s intentional or if it should be standardized across all parsing functions.

  • Files to review:
    • src/core/path-params.ts – uses (error as ZodError).issues
    • src/core/body.ts – both PARSE_FORM_DATA and one occurrence of PARSE_REQUEST_BODY use (error as ZodError).issues while another occurrence uses result.error?.issues
    • src/core/search-params.ts – uses (error as ZodError).issues

console.log((error as ZodError).issues);
}
throw new Error("PARSE_PATH_PARAMS");
throw new Error("PARSE_PATH_PARAMS", { cause: (error as ZodError).issues });
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Technically in this case, ZodError will always be there since it's going to be the error type of safeParse.

In the future, perhaps we can structure this function in such a way that the error will always be a ZodError without relying on type assertions! 👍

@omermecitoglu
Copy link
Owner

Can you edit the commit message using conventional commits

@lauslim12
Copy link
Contributor Author

@omermecitoglu I fixed it, let me know if there's anything else that needs to be changed!

@omermecitoglu omermecitoglu merged commit 3db21e6 into omermecitoglu:main Mar 4, 2025
1 check passed
@omermecitoglu
Copy link
Owner

Thanks for contributing 🥂

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