Skip to content

Conversation

@mfts
Copy link
Owner

@mfts mfts commented May 15, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling for Notion page uploads, ensuring users receive clear error messages if an upload fails.
    • Enhanced feedback for document creation failures, providing more informative error notifications.

@vercel
Copy link

vercel bot commented May 15, 2025

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

Name Status Preview Comments Updated (UTC)
papermark ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 15, 2025 10:47am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 15, 2025

Walkthrough

Explicit error handling was added to both the Notion upload process in the document modal and the document creation utility. Now, when the API response is not successful, the error message is extracted from the response JSON and surfaced to the user, preventing further processing and unhandled exceptions.

Changes

File(s) Change Summary
components/documents/add-document-modal.tsx Added explicit error handling for Notion page upload API calls, displaying error messages via toast.
lib/documents/create-document.ts Improved error handling by throwing errors with parsed JSON messages from failed API responses.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AddDocumentModal
    participant NotionAPI
    participant Toast

    User->>AddDocumentModal: Initiate Notion page upload
    AddDocumentModal->>NotionAPI: POST Notion page
    NotionAPI-->>AddDocumentModal: Response (OK or Error)
    alt Response not OK
        AddDocumentModal->>NotionAPI: Parse error message from JSON
        AddDocumentModal->>Toast: Show error message
        AddDocumentModal-->>User: Stop further processing
    else Response OK
        AddDocumentModal->>AddDocumentModal: Continue with document logic
    end
Loading

Poem

A hop and a jump, with errors in sight,
Now handled with care, and surfaced just right.
No more silent fails, or mysteries to chase,
Toasts pop up swiftly, right in your face!
With JSON in paw, this bunny’s on track—
Uploads and docs, no bugs to come back!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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: 1

🧹 Nitpick comments (3)
lib/documents/create-document.ts (2)

88-90: Inconsistent error handling across functions.

This function uses a different error handling approach than the updated one above (line 51-54). For consistency, consider updating this error handler to match the improved approach used in createDocument.

if (!response.ok) {
-  throw new Error(`HTTP error! status: ${response.status}`);
+  const error = await response.json();
+  throw new Error(typeof error === 'string' ? error : error.message || JSON.stringify(error));
}

125-127: Inconsistent error handling across functions.

This function also uses a different error handling approach than the updated one in createDocument. For consistency, consider updating this error handler as well.

if (!response.ok) {
-  throw new Error(`HTTP error! status: ${response.status}`);
+  const error = await response.json();
+  throw new Error(typeof error === 'string' ? error : error.message || JSON.stringify(error));
}
components/documents/add-document-modal.tsx (1)

365-433: Catch potential JSON parsing errors.

If the response isn't valid JSON, the current implementation might throw uncaught exceptions. Consider adding a try-catch block around JSON parsing to handle potential errors more gracefully.

Wrap the response parsing in try-catch:

try {
  setUploading(true);

  const response = await fetch(
    `/api/teams/${teamInfo?.currentTeam?.id}/documents`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name: createNotionFileName(),
        url: notionLink,
        numPages: 1,
        type: "notion",
        createLink: false,
        folderPathName: currentFolderPath?.join("/"),
      }),
    },
  );

+  let responseData;
+  try {
    if (!response.ok) {
-      const { error } = await response.json();
+      responseData = await response.json();
+      const { error } = responseData;
      toast.error(error);
      return;
    }

-    const document = await response.json();
+    responseData = responseData || await response.json();
+    const document = responseData;
+  } catch (parseError) {
+    toast.error("Failed to parse server response");
+    console.error("JSON parsing error:", parseError);
+    return;
+  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 4882145 and 1ebaf3a.

📒 Files selected for processing (2)
  • components/documents/add-document-modal.tsx (1 hunks)
  • lib/documents/create-document.ts (1 hunks)
🔇 Additional comments (2)
components/documents/add-document-modal.tsx (2)

366-370: Good error handling improvement for Notion uploads.

Adding explicit error handling for failed Notion page uploads is a great improvement, ensuring users receive helpful error messages rather than unexpected failures.


371-372: 🛠️ Refactor suggestion

Potential redundant JSON parsing.

Since the response body stream can only be consumed once, this second call to response.json() might fail if the error branch was executed previously. Consider storing the parsed result after the first check.

if (!response.ok) {
  const { error } = await response.json();
  toast.error(error);
  return;
}

-const document = await response.json();
+const responseData = await response.json();
+const document = responseData;

Likely an incorrect or invalid review comment.

Comment on lines 51 to 54
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
const error = await response.json();
throw new Error(error);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improved error handling, but consider refining further.

The change enhances error handling by extracting error details from the response JSON, but there are a couple of concerns:

  1. Passing an object directly to the Error constructor might result in "[object Object]" as the error message.
  2. No error handling if the response body isn't valid JSON.
if (!response.ok) {
  const error = await response.json();
-  throw new Error(error);
+  throw new Error(typeof error === 'string' ? error : error.message || JSON.stringify(error));
}
🤖 Prompt for AI Agents
In lib/documents/create-document.ts around lines 51 to 54, the error handling
currently throws a new Error with the entire error object, which results in an
unhelpful "[object Object]" message and lacks handling for invalid JSON
responses. To fix this, parse the response JSON inside a try-catch block,
extract a meaningful error message string from the parsed object, and throw a
new Error with that message. If parsing fails, throw a generic error indicating
the response could not be parsed.

@mfts mfts merged commit 7dfd0c9 into main May 15, 2025
4 checks passed
@github-actions github-actions bot locked and limited conversation to collaborators May 15, 2025
@mfts mfts deleted the fix/notion-unpublished branch August 19, 2025 07:59
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants