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

chore: more elaborate response log when API request fails #1000

Merged
merged 6 commits into from
Oct 8, 2024

Conversation

juliusmarminge
Copy link
Collaborator

@juliusmarminge juliusmarminge commented Oct 7, 2024

just attaching response as a log annotation doesn't include the response body if it hasn't been consumed yet. this PR adds a helper that unwraps body for better debug info

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for upload requests, providing clearer insights into failures.
    • Improved logging for both successful and erroneous API responses.
  • Bug Fixes

    • Streamlined error logging for HTTP client interactions, promoting clearer and more maintainable logs.

Copy link

changeset-bot bot commented Oct 7, 2024

⚠️ No Changeset found

Latest commit: 4687ba0

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@juliusmarminge juliusmarminge added the release canary Trigger a canary release to npm label Oct 7, 2024
Copy link

vercel bot commented Oct 7, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs-uploadthing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 11:37pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
legacy-docs-uploadthing ⬜️ Ignored (Inspect) Visit Preview Oct 7, 2024 11:37pm

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

Walkthrough

The changes in this pull request enhance error handling across several functions within the packages/uploadthing/src/internal and packages/uploadthing/src/sdk directories. The logHttpClientError and logHttpClientResponse functions are introduced to centralize HTTP client error logging, replacing inline error handling in the handleCallbackRequest and handleUploadAction functions. Additionally, the UTApi class's requestUploadThing method is updated to utilize these new logging functions, improving clarity in log outputs and maintaining existing upload functionalities.

Changes

File Path Change Summary
packages/uploadthing/src/internal/handler.ts Added logHttpClientError and logHttpClientResponse functions for centralized error logging in handleCallbackRequest and handleUploadAction.
packages/uploadthing/src/internal/logger.ts Introduced logHttpClientError and logHttpClientResponse functions for structured logging of HTTP client errors and responses.
packages/uploadthing/src/sdk/index.ts Updated error handling in requestUploadThing, refined logging, and modified method signatures for various API methods.

Possibly related PRs

  • chore: tap -> tapBoth with error logs when callback forwarding fails #961: This PR enhances error handling and logging in the handleUploadAction function, which is directly related to the changes made in the handleUploadAction function in the main PR, where error handling was also updated to use logHttpClientError.
  • fix: UTApi.getFileUrls send as array #1001: This PR modifies the UTApi class in index.ts, which is part of the same SDK as the changes in the main PR. It includes updates to logging practices in the requestUploadThing method, aligning with the main PR's focus on enhancing logging mechanisms.

Suggested labels

📚 documentation

Suggested reviewers

  • markflorkowski

Poem

🐇 In the realm of uploads, swift and bright,
Errors now whisper, no longer a fright.
With logs that reveal, each detail in sight,
Our API dances, in the soft moonlight.
Hops of improvement, we celebrate here,
A robust little client, we hold so dear! 🌟


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.

@github-actions github-actions bot added the sdk label Oct 7, 2024
Copy link

pkg-pr-new bot commented Oct 7, 2024

Copy link
Contributor

github-actions bot commented Oct 7, 2024

A new canary is available for testing. You can install this latest build in your project with:

pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add [email protected]
pnpm add @uploadthing/[email protected]

@github-actions github-actions bot removed the release canary Trigger a canary release to npm label Oct 7, 2024
Copy link
Contributor

github-actions bot commented Oct 7, 2024

📦 Bundle size comparison

Bundle Size (gzip) Visualization
Main 26.04KB See Treemap 📊
PR (268c6eb) 26.04KB See Treemap 📊
Diff No change

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 68d7d31 and ad48ddc.

📒 Files selected for processing (1)
  • packages/uploadthing/src/sdk/index.ts (1 hunks)
🧰 Additional context used

packages/uploadthing/src/sdk/index.ts Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (1)
packages/uploadthing/src/internal/logger.ts (1)

56-65: LGTM! Consider adding documentation and improving error handling.

The logHttpClientError function is well-implemented and consistent with the existing codebase. It provides a flexible way to log HTTP client errors with different levels of detail based on the error type.

Consider adding JSDoc comments to explain the function's purpose, parameters, and return value. This will improve code maintainability and make it easier for other developers to understand and use the function.

The JSON parsing in the "ResponseError" case could benefit from more robust error handling. Consider wrapping the json parsing in a try-catch block to handle potential parsing errors gracefully. Here's a suggested improvement:

export const logHttpClientError =
  (message: string) =>
  (err: HttpClientError.HttpClientError | HttpBody.HttpBodyError) =>
    err._tag === "ResponseError"
      ? Effect.flatMap(
          Effect.tryPromise(() => err.response.json()),
          (json) =>
            Effect.logError(`${message} (${err.response.status})`).pipe(
              Effect.annotateLogs("response", json),
            ),
        ).pipe(
          Effect.catchAll((parseError) =>
            Effect.logError(`${message} (${err.response.status})`).pipe(
              Effect.annotateLogs("error", "Failed to parse response JSON"),
              Effect.annotateLogs("parseError", parseError),
            ),
          ),
        )
      : Effect.logError(message).pipe(Effect.annotateLogs("error", err));

This change ensures that even if JSON parsing fails, we still log the error message and status code, along with information about the parsing failure.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ad48ddc and 9b9bd94.

📒 Files selected for processing (3)
  • packages/uploadthing/src/internal/handler.ts (4 hunks)
  • packages/uploadthing/src/internal/logger.ts (2 hunks)
  • packages/uploadthing/src/sdk/index.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/uploadthing/src/sdk/index.ts
🧰 Additional context used
🔇 Additional comments (7)
packages/uploadthing/src/internal/logger.ts (2)

1-1: LGTM! Imports are correctly added and utilized.

The new imports for HttpBody and HttpClientError from "@effect/platform" are appropriately added and used in the logHttpClientError function. This maintains consistency with the existing codebase's use of the Effect library.


Line range hint 1-65: Summary: Enhanced error logging aligns with PR objectives

The addition of the logHttpClientError function successfully addresses the PR's objective of providing more elaborate response logging when API requests fail. This implementation:

  1. Integrates seamlessly with the existing logging infrastructure.
  2. Provides detailed error information for both HTTP client errors and response body parsing errors.
  3. Maintains consistency with the codebase's use of the Effect library for logging and error handling.

These changes will significantly improve debugging capabilities for API request failures, making it easier to identify and resolve issues in production environments.

packages/uploadthing/src/internal/handler.ts (5)

34-38: LGTM: Import changes enhance error logging capabilities

The addition of logHttpClientError import aligns well with the PR objective of improving error logging. The grouping with other logging-related imports maintains good code organization.


386-387: Excellent: Improved error handling in handleCallbackRequest

The use of logHttpClientError here centralizes error logging and provides more detailed information when registering the callback result fails. This change enhances maintainability and aligns perfectly with the PR's objective of improving API request failure logging.


620-620: Great: Consistent error handling in handleUploadAction

The use of logHttpClientError for metadata registration errors maintains consistency with the earlier changes. This further centralizes error logging and improves the overall error handling approach in the file.


657-663: Excellent: Enhanced error logging for dev stream callback requests

The use of logHttpClientError here maintains consistency with earlier changes. The addition of context (hook, signature, payload) to the error log significantly enhances debugging capabilities for development-related issues.


Line range hint 1-693: Summary: Excellent improvements in error logging across the file

The changes in this file consistently implement the use of logHttpClientError for various API request failure scenarios. This enhancement aligns perfectly with the PR's objective of providing more elaborate response logs. The consistent application of this logging approach across different functions (handleCallbackRequest, handleUploadAction, and dev stream error handling) improves code maintainability and debugging capabilities.

These modifications will significantly aid in troubleshooting API-related issues by providing more detailed and context-rich error logs.

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

🧹 Outside diff range and nitpick comments (2)
packages/uploadthing/src/internal/logger.ts (2)

62-80: LGTM with a suggestion: Consider adding error handling for body extraction.

The logHttpClientResponse function is well-implemented, providing flexibility in logging level and response body format. However, consider adding error handling for the body extraction process.

Consider wrapping the body extraction in a try-catch or using Effect.tryPromise to handle potential errors:

return (response: HttpClientResponse.HttpClientResponse) =>
  Effect.tryPromise({
    try: () => mixin !== "None" ? response[mixin]() : Promise.resolve(),
    catch: (error) => new Error(`Failed to extract response body: ${error}`),
  }).pipe(
    Effect.flatMap(() =>
      Effect.logWithLevel(level, `${message} (${response.status})`).pipe(
        Effect.annotateLogs("response", response),
      )
    ),
    Effect.catchAll((error) =>
      Effect.logError(`Error logging response: ${error.message}`).pipe(
        Effect.annotateLogs("error", error),
        Effect.annotateLogs("response", response),
      )
    )
  );

This change would ensure that any errors during body extraction are caught and logged, providing more robust error handling.


82-87: LGTM with suggestions: Consider improving error type handling.

The logHttpClientError function effectively differentiates between ResponseError and other error types, and reuses logHttpClientResponse for consistency. However, there's room for improvement in error type narrowing and handling.

Consider the following improvements:

  1. Use type predicates for more precise error type checking:
const isResponseError = (
  err: HttpClientError.HttpClientError | HttpBody.HttpBodyError
): err is HttpClientError.ResponseError => err._tag === "ResponseError";

export const logHttpClientError =
  (message: string) =>
  (err: HttpClientError.HttpClientError | HttpBody.HttpBodyError) =>
    isResponseError(err)
      ? logHttpClientResponse(message, { level: "Error" })(err.response)
      : Effect.logError(message).pipe(
          Effect.annotateLogs("error", err),
          Effect.annotateLogs("errorType", err._tag)
        );
  1. Consider adding more specific error handling for different error types:
export const logHttpClientError =
  (message: string) =>
  (err: HttpClientError.HttpClientError | HttpBody.HttpBodyError) => {
    if (isResponseError(err)) {
      return logHttpClientResponse(message, { level: "Error" })(err.response);
    } else if (err._tag === "RequestError") {
      return Effect.logError(`${message}: Request failed`).pipe(
        Effect.annotateLogs("error", err),
        Effect.annotateLogs("errorType", "RequestError")
      );
    } else {
      return Effect.logError(`${message}: Unknown error`).pipe(
        Effect.annotateLogs("error", err),
        Effect.annotateLogs("errorType", err._tag)
      );
    }
  };

These changes would provide more precise error handling and logging, making debugging easier.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9b9bd94 and a8f1c1d.

📒 Files selected for processing (3)
  • packages/uploadthing/src/internal/handler.ts (3 hunks)
  • packages/uploadthing/src/internal/logger.ts (2 hunks)
  • packages/uploadthing/src/sdk/index.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/uploadthing/src/sdk/index.ts
🧰 Additional context used
🔇 Additional comments (3)
packages/uploadthing/src/internal/logger.ts (2)

1-5: LGTM: New imports and type definition look good.

The new imports from "@effect/platform" and the HttpClientResponseMixinMethod type definition are appropriate for the new logging functions introduced in this file.

Also applies to: 60-60


Line range hint 1-87: Summary: Good implementation with room for minor improvements.

Overall, the changes in this file significantly enhance the error handling and logging capabilities, aligning well with the PR objectives. The new logHttpClientResponse and logHttpClientError functions provide more elaborate and flexible response logging, which will improve debugging.

Some suggestions for improvements have been made:

  1. Adding error handling for body extraction in logHttpClientResponse.
  2. Improving error type handling and narrowing in logHttpClientError.

These suggestions, if implemented, would further enhance the robustness and precision of the logging system.

packages/uploadthing/src/internal/handler.ts (1)

34-39: Centralized logging functions imported successfully

The addition of logHttpClientError, logHttpClientResponse, withLogFormat, and withMinimalLogLevel imports improves the codebase by centralizing logging logic, enhancing maintainability and readability.

),
),
onFalse: () =>
metadataRequest.pipe(
Effect.tapBoth({
onSuccess: logHttpClientResponse("Registerred metadata"),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Typo in log message: 'Registerred' should be 'Registered'

Apply this diff to correct the typo:

-onSuccess: logHttpClientResponse("Registerred metadata"),
+onSuccess: logHttpClientResponse("Registered metadata"),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onSuccess: logHttpClientResponse("Registerred metadata"),
onSuccess: logHttpClientResponse("Registered metadata"),

packages/uploadthing/src/internal/handler.ts Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (4)
packages/uploadthing/src/internal/handler.ts (4)

387-388: Improved error handling in handleCallbackRequest

The use of logHttpClientError for error logging is a good improvement. It centralizes the error handling logic and makes the code more consistent.

Consider making the error message more specific:

-          logHttpClientError("Failed to register callback result"),
+          logHttpClientError("Failed to register callback result in handleCallbackRequest"),

This will make it easier to identify the source of the error in logs.


624-629: Enhanced logging in handleUploadAction

The use of logHttpClientResponse and logHttpClientError within a tapBoth effect is a good improvement. It ensures comprehensive logging for both success and failure cases without interfering with the main function flow.

Consider making the success message more specific:

-            onSuccess: logHttpClientResponse("Registered metadata", {
+            onSuccess: logHttpClientResponse("Successfully registered metadata in handleUploadAction", {

This will provide more context in the logs, making it easier to trace the flow of operations.


641-648: Improved logging for callback request forwarding

The use of logHttpClientResponse and logHttpClientError within a tapBoth effect for callback request forwarding is a good improvement. It ensures comprehensive logging for both success and failure cases.

Consider making the error message more specific:

-                  "Failed to forward callback request from dev stream",
+                  "Failed to forward callback request from dev stream in handleUploadAction",

This will provide more context in the logs, making it easier to identify the source of the error.


658-661: Enhanced logging for metadata registration

The use of logHttpClientResponse and logHttpClientError within a tapBoth effect for metadata registration is a good improvement. It ensures comprehensive logging for both success and failure cases.

Consider making both messages more specific:

-            onSuccess: logHttpClientResponse("Registered metadata"),
-            onFailure: logHttpClientError("Failed to register metadata"),
+            onSuccess: logHttpClientResponse("Successfully registered metadata in handleUploadAction"),
+            onFailure: logHttpClientError("Failed to register metadata in handleUploadAction"),

This will provide more context in the logs, making it easier to trace the flow of operations and identify the source of any errors.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a8f1c1d and 4687ba0.

📒 Files selected for processing (1)
  • packages/uploadthing/src/internal/handler.ts (3 hunks)
🧰 Additional context used
🔇 Additional comments (3)
packages/uploadthing/src/internal/handler.ts (3)

34-39: Improved error handling with centralized logging

The addition of logHttpClientError and logHttpClientResponse imports from the "./logger" module is a positive change. This centralization of logging functions will lead to more consistent error handling and logging across the codebase, making it easier to maintain and debug.


Line range hint 1-686: Overall improvements in error handling and logging

The changes in this file significantly improve error handling and logging by consistently implementing centralized logging functions. This will make the code more maintainable and easier to debug. Great job on these improvements!

Remember to address the typo in the "Registered metadata" log message as mentioned in the previous comment.


625-625: ⚠️ Potential issue

Typo in log message persists

The typo in the log message still exists:

-            onSuccess: logHttpClientResponse("Registerred metadata", {
+            onSuccess: logHttpClientResponse("Registered metadata", {

This typo was mentioned in a previous review. Please ensure to correct it in this update.

Copy link
Contributor

github-actions bot commented Oct 8, 2024

A new canary is available for testing. You can install this latest build in your project with:

pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add @uploadthing/[email protected]
pnpm add [email protected]
pnpm add @uploadthing/[email protected]

@github-actions github-actions bot removed the release canary Trigger a canary release to npm label Oct 8, 2024
@juliusmarminge juliusmarminge merged commit 8ae602d into main Oct 8, 2024
24 checks passed
@juliusmarminge juliusmarminge deleted the sdk-response-log branch October 8, 2024 21:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant