Skip to content

Conversation

@omermecitoglu
Copy link
Owner

@omermecitoglu omermecitoglu commented Oct 18, 2024

Summary by CodeRabbit

  • New Features

    • Introduced an optional handleErrors property for custom error handling in route definitions.
    • Enhanced error context in parsing functions to provide more informative error messages.
  • Bug Fixes

    • Improved error handling for various parsing scenarios, allowing for more specific error responses.
  • Tests

    • Added new test cases for the defineRoute function to validate custom error handling for expected and unexpected errors.
  • Documentation

    • Updated README.md to include details on the new handleErrors property and example usage.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 18, 2024

Walkthrough

The pull request introduces enhancements to error handling in the @omer-x/next-openapi-route-handler package. A new optional property, handleErrors, is added to the defineRoute function, allowing users to implement custom error handlers. Modifications in several source files improve error reporting by including detailed causes in error objects. Additionally, new test cases validate the functionality of the handleErrors property, ensuring that both expected and unexpected errors can be managed effectively.

Changes

File Change Summary
README.md Added handleErrors property to defineRoute function; updated example usage.
src/core/body.ts Enhanced parseRequestBody to include cause in thrown errors; added specific handling for JSON parsing errors.
src/core/definer.test.ts Introduced new tests for defineRoute focusing on custom error handling for expected and unexpected errors.
src/core/definer.ts Added handleErrors to RouteOptions; updated error handling logic to utilize this property.
src/core/search-params.ts Modified parseSearchParams to include cause in thrown errors for better context.
src/types/error.ts Added customErrorTypes constant containing various error types related to parsing operations.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Server
    participant ErrorHandler

    User->>Server: Make a request
    Server->>Server: Process request
    alt Error occurs
        Server->>ErrorHandler: Call handleErrors(errorType, issues)
        ErrorHandler-->>Server: Return custom Response
    else No Error
        Server-->>User: Return successful Response
    end
Loading

🐰 "In the code where errors may dwell,
Custom handlers now ring a bell.
With causes clear and types defined,
Our routes are stronger, well-aligned!
So hop along, let's code with glee,
For error handling is now error-free!" 🐇


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

@omermecitoglu omermecitoglu linked an issue Oct 18, 2024 that may be closed by this pull request
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: 4

🧹 Outside diff range and nitpick comments (6)
src/types/error.ts (1)

1-7: LGTM! Consider adding JSDoc comments.

The implementation of customErrorTypes looks good. The use of as const ensures type safety for the string literals. To improve documentation, consider adding JSDoc comments explaining the purpose and usage of this constant.

Here's a suggested addition:

/**
 * Defines a set of custom error types related to parsing operations.
 * These types can be used for specific error handling in request processing.
 */
export const customErrorTypes = [
  // ... (existing code)
];
src/core/search-params.ts (1)

22-22: Approved: Enhanced error reporting with a minor suggestion.

The change improves error handling by including the ZodError issues as the cause of the thrown error. This enhancement aligns with the PR objective and provides more context for debugging.

For improved type safety, consider using a type assertion or type guard before accessing the issues property:

throw new Error("PARSE_SEARCH_PARAMS", { 
  cause: error instanceof ZodError ? error.issues : error 
});

This ensures that cause is always set, even if the caught error is not a ZodError.

src/core/body.ts (1)

43-46: Improved handling of empty JSON input.

The new conditional check for "Unexpected end of JSON input" error enhances the function's robustness by handling cases where the request body is empty. This approach provides more informative error reporting for this specific scenario.

Consider adding a brief comment explaining why this specific case is handled differently, for example:

+    // Handle empty request body case
     if (error instanceof Error && error.message === "Unexpected end of JSON input") {
       const result = schema.safeParse({});
       throw new Error("PARSE_REQUEST_BODY", { cause: result.error?.issues });
     }
README.md (2)

57-57: Consider expanding the description for handleErrors.

The addition of the handleErrors property is well-documented. However, to provide more clarity for users, consider expanding the description slightly.

Suggested improvement:

- | handleErrors  | (errorType: string, issues?: [ZodIssues](https://zod.dev/ERROR_HANDLING?id=zodissue)[]) => Response | `(Optional)` Custom error handler can be provided to replace the default behavior. [See below](#example) |
+ | handleErrors  | (errorType: string, issues?: [ZodIssues](https://zod.dev/ERROR_HANDLING?id=zodissue)[]) => Response | `(Optional)` Custom error handler function to replace the default error handling behavior. It receives the error type and optional Zod validation issues. [See example below](#example) for usage. |

102-116: Great example, consider adding a default case.

The example effectively demonstrates the usage of the new handleErrors property. It covers all the possible error types and provides a clear implementation.

To make the example even more robust, consider adding a default case to the switch statement:

  handleErrors: (errorType, issues) => {
    console.log(issues);
    switch (errorType) {
      case "PARSE_FORM_DATA":
      case "PARSE_REQUEST_BODY":
      case "PARSE_SEARCH_PARAMS":
        return new Response(null, { status: 400 });
      case "PARSE_PATH_PARAMS":
        return new Response(null, { status: 404 });
      case "UNNECESSARY_PATH_PARAMS":
      case "UNKNOWN_ERROR":
        return new Response(null, { status: 500 });
+     default:
+       return new Response(null, { status: 500 });
    }
  },

This ensures that all possible cases are handled, even if new error types are introduced in the future.

src/core/definer.test.ts (1)

265-267: Leverage _errorType and _cause in handleErrors

The parameters _errorType and _cause in your handleErrors function are currently unused. To enhance error handling, consider utilizing these parameters to provide more specific responses or to log detailed error information.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between af9ff62 and 656d06e.

📒 Files selected for processing (6)
  • README.md (2 hunks)
  • src/core/body.ts (1 hunks)
  • src/core/definer.test.ts (1 hunks)
  • src/core/definer.ts (4 hunks)
  • src/core/search-params.ts (1 hunks)
  • src/types/error.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (8)
src/core/body.ts (3)

37-37: Improved error handling for form data parsing.

The addition of the cause property to the thrown error enhances error reporting by including detailed ZodError issues. This change allows for more effective debugging and error handling in the calling code.


51-51: Consistent error handling for JSON parsing.

The addition of the cause property to the thrown error in the JSON parsing section maintains consistency with the form data parsing error handling. This change enhances error reporting by including detailed ZodError issues, facilitating better debugging and error handling in the calling code.


37-51: Overall improvement in error handling and reporting.

The changes in this file consistently enhance error handling and reporting across different parsing scenarios (form data and JSON). By including detailed error information in the cause property of thrown errors, these modifications provide valuable context for debugging and custom error handling. This aligns well with the PR objective of implementing a custom error handler feature.

README.md (1)

Line range hint 1-116: Overall, excellent documentation of the new feature.

The changes to the README.md file effectively introduce and explain the new handleErrors feature. The documentation is clear, concise, and includes a helpful example of usage. The minor suggestions provided will further enhance the clarity and robustness of the documentation.

src/core/definer.ts (3)

1-1: Import of 'customErrorTypes' is correctly added

The import statement for customErrorTypes from "~/types/error" is appropriate and correctly implemented.


10-10: Import of 'Zod' types is accurate

The types ZodIssue, ZodType, and ZodTypeDef are correctly imported from "zod".


48-48: Addition of 'handleErrors' enhances error handling flexibility

The optional handleErrors property in the RouteOptions type allows for custom error handling, improving the flexibility and robustness of the defineRoute function.

src/core/definer.test.ts (1)

296-300: 🛠️ Refactor suggestion

Ensure consistency of errorType values

In your handleErrors function, you check if errorType === "UNKNOWN_ERROR". Verify that "UNKNOWN_ERROR" is the correct and consistent value used by your error handling system for unexpected errors. Consider defining error types as constants or enums to prevent typos and improve maintainability.

Run the following script to check all occurrences of errorType values:

✅ Verification successful

Consistency of errorType Values Verified

All instances of errorType comparisons use the consistent value "UNKNOWN_ERROR". No discrepancies found in the error handling system.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all unique `errorType` values used in the codebase.

# Search for errorType comparisons and extract the literals.
rg --type ts --pcre2 --no-filename --no-line-number "errorType\s*===\s*[\"'](\w+)[\"']" -or '$1' | sort | uniq

Length of output: 130

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 656d06e and ff50a03.

📒 Files selected for processing (1)
  • src/core/definer.test.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
src/core/definer.test.ts (2)

248-276: LGTM!

The test case is well-written and effectively tests the custom error handler for an expected error scenario.


278-309: LGTM!

The test case correctly verifies the custom error handler for an unexpected error scenario.

@omermecitoglu omermecitoglu merged commit ff50a03 into main Oct 21, 2024
1 check passed
@coderabbitai coderabbitai bot mentioned this pull request Oct 23, 2024
@omermecitoglu omermecitoglu deleted the feat/custom-error-handler branch November 7, 2024 01:50
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.

No output when request body is invalid

2 participants