Skip to content
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

Add custom err handler #207

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Add custom err handler #207

wants to merge 2 commits into from

Conversation

fabiante
Copy link
Owner

@fabiante fabiante commented Oct 20, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new error handling mechanism that improves how errors are managed and reported within the application.
    • Updated routing to enhance error handling for specific endpoints.
  • Bug Fixes

    • Improved error reporting by ensuring that error information is returned when resolution fails.
  • Documentation

    • Enhanced clarity on error handling processes within the API.

@fabiante fabiante marked this pull request as ready for review October 20, 2024 10:19
Copy link

coderabbitai bot commented Oct 20, 2024

Walkthrough

The changes introduce a new error handling mechanism in the API, enhancing the way errors are managed across different components. A new type ErrHandler is defined, along with a function AsErrHandler that wraps handlers to handle errors more effectively. The Resolve method in Server is updated to return an error, providing better error reporting. Additionally, the routing setup in server_routes.go is modified to utilize the new error handling by wrapping the Resolve method with AsErrHandler.

Changes

File Change Summary
api/err.go Added type ErrHandler func(c *gin.Context) error and func AsErrHandler(h ErrHandler) gin.HandlerFunc.
api/server.go Updated Resolve method signature to return error and modified error handling logic.
api/server_routes.go Replaced s.Resolve with AsErrHandler(s.Resolve) in the routing setup for /:domain/:name.

Poem

In the land of code where errors roam,
A rabbit found a way to bring them home.
With ErrHandler now in play,
No more errors lead us astray!
So hop along, let’s cheer and sing,
For better handling is a wonderful thing! 🐇✨


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.

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: 2

🧹 Outside diff range and nitpick comments (1)
api/err.go (1)

20-29: Approve with suggestions: Enhance error handling in AsErrHandler

The AsErrHandler function effectively wraps the custom ErrHandler into a Gin-compatible HandlerFunc, which is a good approach. However, there are a few suggestions to improve the error handling:

  1. Consider allowing for different status codes instead of always using 500. This could be achieved by either expanding the ErrHandler type to return both an error and a status code, or by implementing custom error types that include status codes.

  2. The return value of ctx.AbortWithError is discarded. Consider logging this error or handling it in some way, as it represents a failure to send the error response to the client.

  3. The current implementation doesn't use the custom error response format defined in respondWithError. Consider using this or a similar approach for consistent error responses across the API.

Here's a potential improvement:

func AsErrHandler(h ErrHandler) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		err := h(ctx)
		if err != nil {
			status := http.StatusInternalServerError
			if se, ok := err.(interface{ StatusCode() int }); ok {
				status = se.StatusCode()
			}
			respondWithError(ctx, status, err)
		}
	}
}

This suggestion allows for custom status codes through error types, uses the existing respondWithError function, and provides more flexible error handling.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c59287e and c1463cb.

📒 Files selected for processing (3)
  • api/err.go (1 hunks)
  • api/server.go (1 hunks)
  • api/server_routes.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (4)
api/err.go (2)

18-18: LGTM: Well-defined error handler type

The ErrHandler type is well-defined and aligns with the Gin framework's context-based approach. It provides a clear interface for error-handling functions, allowing for flexible error management across the API.


Line range hint 1-29: Summary: Solid error handling enhancements with room for minor improvements

The introduced error handling mechanisms in api/err.go significantly enhance the API's capabilities for managing and reporting errors. The ErrHandler type and AsErrHandler function provide a flexible and Gin-compatible approach to error handling.

Key points:

  1. The ErrHandler type is well-defined and aligns with Gin's context-based approach.
  2. The AsErrHandler function effectively wraps custom error handlers into Gin-compatible handlers.
  3. There's room for improvement in error status code handling and response formatting.

Overall, these changes represent a positive step towards more robust error management in the API. Implementing the suggested improvements will further enhance the flexibility and consistency of error handling across the system.

api/server.go (2)

21-21: LGTM: Improved error handling

The changes to the Resolve function signature and the explicit nil returns improve error handling and make the control flow more clear. This is consistent with Go's idiomatic error handling practices.

Also applies to: 29-29, 32-32


21-35: Verify the impact on the rest of the codebase

The changes to the Resolve function signature and behavior might require updates in other parts of the codebase that call this method or depend on its error handling.

Let's run a script to check for potential impacts:

Please review the results of this script to ensure that all necessary updates have been made and that error handling is consistent throughout the codebase.

✅ Verification successful

Impact Verification Successful

The changes to the Resolve method affect only api/server.go:25, and there are no indications of broader impacts on the rest of the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usages of the Resolve method and potential impacts

# Search for Resolve method calls
echo "Searching for Resolve method calls:"
rg -n "\.Resolve\(" --type go

# Search for respondWithError function to ensure it's still used elsewhere
echo "\nChecking if respondWithError is still used:"
rg -n "respondWithError" --type go

# Search for AsErrHandler to see how it's implemented
echo "\nChecking AsErrHandler implementation:"
rg -n "func AsErrHandler" --type go

Length of output: 1545

default:
respondWithError(ctx, http.StatusInternalServerError, err)
return err
Copy link

@coderabbitai coderabbitai bot Oct 20, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider the implications of removing respondWithError

By directly returning the error instead of calling respondWithError, we're no longer immediately responding to the client with an error status. This might lead to inconsistent error responses if not handled properly by the caller.

Consider one of the following options:

  1. Keep the respondWithError call before returning the error.
  2. Ensure that the caller (likely the AsErrHandler wrapper) properly handles all error cases and responds to the client appropriately.

Copy link
Owner Author

Choose a reason for hiding this comment

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

Propose an alteration to AsErrHandler which makes use of a customer error type containing the error message and status to respond with.

Copy link

Choose a reason for hiding this comment

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

@fabiante

Certainly! Here's an updated version of AsErrHandler that uses a custom error type containing the error message and status code:

// Define a custom error type
type HTTPError struct {
    StatusCode int
    Err        error
}

func (e *HTTPError) Error() string {
    return e.Err.Error()
}

// Update AsErrHandler to handle the custom error type
func AsErrHandler(h ErrHandler) gin.HandlerFunc {
    return func(ctx *gin.Context) {
        if err := h(ctx); err != nil {
            // Check if the error is of type *HTTPError
            if httpErr, ok := err.(*HTTPError); ok {
                ctx.AbortWithError(httpErr.StatusCode, httpErr.Err)
            } else {
                ctx.AbortWithError(http.StatusInternalServerError, err)
            }
        }
    }
}

Then, in your handler functions like Resolve, you can return an *HTTPError with the desired status code and error:

func (s *Server) Resolve(ctx *gin.Context) error {
    domain := ctx.Param("domain")
    name := ctx.Param("name")

    target, err := s.resolver.Resolve(domain, name)
    switch {
    case err == nil:
        ctx.Redirect(http.StatusFound, target)
        return nil
    case errors.Is(err, app.ErrNotFound):
        return &HTTPError{
            StatusCode: http.StatusNotFound,
            Err:        err,
        }
    default:
        return &HTTPError{
            StatusCode: http.StatusInternalServerError,
            Err:        err,
        }
    }
}

This approach allows AsErrHandler to respond with the appropriate HTTP status codes based on the custom error returned by your handlers, ensuring consistent and flexible error handling.


✏️ Learnings added
Learnt from: fabiante
PR: fabiante/persurl#207
File: api/server.go:34-34
Timestamp: 2024-10-20T10:36:41.825Z
Learning: In the `api/err.go` file, when using `AsErrHandler` in the Gin framework (Go), prefer using a custom error type (`HTTPError`) that contains the status code and error message to respond with, allowing for consistent and flexible error handling.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@@ -30,7 +30,7 @@ func SetupRouting(r gin.IRouter, s *Server) {

resolve.Use(validDomain, validName)

resolve.GET("/:domain/:name", s.Resolve)
resolve.GET("/:domain/:name", AsErrHandler(s.Resolve))
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Approve and Recommend Expanding Error Handling Consistency

The modification to wrap s.Resolve with AsErrHandler effectively standardizes error handling for this endpoint, enhancing consistency in error responses.

Recommendations:

  1. Extend AsErrHandler Usage: Apply this error handling pattern to other route handlers (e.g., in admin and system groups) to ensure uniform error management across the API.
  2. Update Documentation: Revise the API documentation to outline the standardized error responses provided by AsErrHandler, aiding developers in understanding and utilizing the error handling mechanism effectively.
🔗 Analysis chain

Approve change and suggest consistent application

The modification to wrap s.Resolve with AsErrHandler is a good improvement for standardized error handling. This change likely enhances error reporting and handling consistency for the resolve endpoint.

Consider the following recommendations:

  1. Apply this pattern to other routes (e.g., in the admin and system groups) for consistency across the API.
  2. Update the API documentation to reflect any changes in error responses that may result from using AsErrHandler.

To ensure the change doesn't introduce unexpected behavior, please verify the following:

  1. The implementation of AsErrHandler in api/err.go.
  2. The impact on API responses, especially for error cases.

You can use the following script to check the AsErrHandler implementation and its usage:

This will help ensure that the error handling is implemented correctly and used consistently.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check AsErrHandler implementation and usage

# Check AsErrHandler implementation
echo "AsErrHandler implementation:"
rg -A 10 "func AsErrHandler" api/err.go

# Check AsErrHandler usage across the codebase
echo "\nAsErrHandler usage:"
rg "AsErrHandler\(" api/

Length of output: 500

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