Skip to content

Conversation

@felangel
Copy link
Contributor

@felangel felangel commented Apr 4, 2025

Status

READY

Description

  • fix(dart_frog): add default handler for disallowed http methods
    • This fixes a bug where previously requests made to a dart frog server with arbitrary http methods would result in a 500 (internal server error). With the changes in the PR, that case would result in a 405 (method not allowed)

Type of Change

  • ✨ New feature (non-breaking change which adds functionality)
  • 🛠️ Bug fix (non-breaking change which fixes an issue)
  • ❌ Breaking change (fix or feature that would cause existing functionality to change)
  • 🧹 Code refactor
  • ✅ Build configuration change
  • 📝 Documentation
  • 🗑️ Chore

@felangel felangel requested a review from a team as a code owner April 4, 2025 21:47
@coderabbitai
Copy link

coderabbitai bot commented Apr 4, 2025

Walkthrough

The changes enhance error handling for unsupported HTTP methods. A new exception class, UnsupportedHttpMethodException, is added in the request module to explicitly signal unsupported methods. The Request class now throws this exception when a non-supported method is encountered. Meanwhile, the Router class is updated to include a methodNotAllowedHandler parameter and internal logic that catches the exception to return a 405 response. Additional tests are included to validate the behavior, and error handling in the CLI e2e tests is refined to catch specific exception types.

Changes

File(s) Change Summary
packages/dart_frog/lib/src/request.dart
packages/dart_frog/lib/src/router.dart
Introduced UnsupportedHttpMethodException; updated Request's method getter to throw this exception; enhanced Router to accept a new methodNotAllowedHandler, added default handler _defaultMethodNotAllowed, and introduced _MethodNotAllowedResponse for 405 responses.
packages/dart_frog/test/src/request_test.dart
packages/dart_frog/test/src/router_test.dart
Added tests to verify that unsupported HTTP methods throw the proper exception in Request and result in a 405 response in Router; tests ensure consistency for response methods (body(), bytes(), and copyWith()).
packages/dart_frog_cli/e2e/test/dev_test.dart Refined error handling by replacing generic catch blocks with exception-specific (on Exception) catch blocks in multiple locations.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant R as Router
    participant Req as Request
    participant H as MethodNotAllowedHandler

    C->>R: Send HTTP request
    R->>Req: Retrieve request.method
    Req-->>R: Throw UnsupportedHttpMethodException
    R->>H: Call methodNotAllowedHandler
    H-->>R: Return 405 Method Not Allowed response
    R->>C: Send response
Loading

Poem

I'm a rabbit hoppin' through the code,
Finding bugs and easing heavy loads.
Unsupported methods now get a friendly beep—
A 405 response to help our system keep.
With tests that pass and errors now in sight,
I celebrate these fixes with pure delight!


📜 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 acc6829 and 1a85f67.

📒 Files selected for processing (5)
  • packages/dart_frog/lib/src/request.dart (2 hunks)
  • packages/dart_frog/lib/src/router.dart (5 hunks)
  • packages/dart_frog/test/src/request_test.dart (2 hunks)
  • packages/dart_frog/test/src/router_test.dart (2 hunks)
  • packages/dart_frog_cli/e2e/test/dev_test.dart (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: docker_custom / test
  • GitHub Check: pana / build
  • GitHub Check: build / build
  • GitHub Check: pana / build
  • GitHub Check: e2e (ubuntu-latest)
  • GitHub Check: e2e (windows-latest)
  • GitHub Check: e2e (macos-latest)
🔇 Additional comments (14)
packages/dart_frog/test/src/request_test.dart (2)

6-6: Good addition of necessary import

Adding the import for package:dart_frog/src/_internal.dart is necessary to access the new UnsupportedHttpMethodException class.


47-59: Well-structured test for unsupported HTTP method handling

This test thoroughly verifies the behavior when an unsupported HTTP method is encountered. It checks both the exception type and the formatting of the error message. The test ensures that the Request class correctly rejects invalid HTTP methods and provides a helpful error message with supported alternatives.

packages/dart_frog/lib/src/request.dart (2)

3-18: Good implementation of custom exception class

The UnsupportedHttpMethodException class is well-implemented with:

  • Clear documentation using Dart doc commenting conventions
  • A simple constructor that takes the unsupported method
  • A well-formatted toString() method that provides a helpful error message including the list of supported methods

This enhancement improves error clarity and user experience by providing specific information about unsupported HTTP methods.


132-135: Improved error handling in method getter

The refactored method getter now properly throws an UnsupportedHttpMethodException when an unsupported HTTP method is encountered. Using firstWhere with orElse is an elegant pattern for this use case.

This change improves the robustness of the API by providing clear error handling rather than potentially returning unexpected results for unsupported methods.

packages/dart_frog_cli/e2e/test/dev_test.dart (2)

87-87: More precise exception handling

Changing from a generic catch (e) to a specific on Exception catch (e) makes the error handling more precise. This ensures that only proper Exception classes are caught, while other errors (like programming errors or assertion failures) will still propagate.


134-134: More precise exception handling in ignoreErrors method

Similarly, updating the catch clause in the ignoreErrors extension method to only catch Exception types improves the precision of error handling. This aligns with the overall approach of handling specific exception types differently from other errors.

packages/dart_frog/test/src/router_test.dart (2)

94-100: Good test for handling unsupported HTTP methods

This test properly verifies that the router returns a 405 Method Not Allowed status code and the correct error message when an unsupported HTTP method is used. Using the 'FOO' method is a good choice for testing unsupported methods.

The test ensures that the integration between the UnsupportedHttpMethodException and the router's handling works correctly.


455-473: Comprehensive tests for methodNotAllowed response

These tests ensure that the Router.methodNotAllowed response behaves consistently:

  1. The body() method returns the expected message and can be called multiple times
  2. The bytes() method emits the expected encoded message and can be called multiple times
  3. The copyWith() method preserves the response body while allowing header modifications

This test pattern matches the existing tests for Router.routeNotFound, maintaining consistency in the test approach.

packages/dart_frog/lib/src/router.dart (6)

39-46: Well-structured constructor update with appropriate documentation

The constructor now includes the methodNotAllowedHandler parameter with clear documentation explaining its purpose. The default value _defaultMethodNotAllowed follows the same pattern as the existing notFoundHandler parameter, making this a consistent implementation.


57-57: Good addition of the handler field

The new field _methodNotAllowedHandler is properly declared as final and aligns with the existing pattern used for _notFoundHandler.


177-184: Robust error handling for unsupported HTTP methods

This change properly handles the case where an unsupported HTTP method is encountered. The try-catch block specifically catches UnsupportedHttpMethodException and routes to the appropriate handler, enhancing the framework's error handling capabilities.


227-229: Simple and consistent implementation of default handler

The _defaultMethodNotAllowed static method follows the same pattern as the existing _defaultNotFound method, returning a constant response object.


237-243: Well-documented sentinel response object

The static methodNotAllowed field and its documentation follow the same pattern as the existing routeNotFound field, maintaining consistency in the codebase.


268-289: Well-implemented response class for method not allowed

The _MethodNotAllowedResponse class correctly extends Response and sets the appropriate status code (HttpStatus.methodNotAllowed). The implementation closely mirrors the existing _RouteNotFoundResponse class, providing all necessary method overrides to ensure consistent behavior.


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

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.

@felangel felangel closed this Apr 4, 2025
@felangel felangel deleted the fix/default-method-not-allowed-handler branch April 4, 2025 22:02
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.

1 participant