Skip to content

Add user-friendly error handling for OpenAI API responses#8

Merged
heymaaz merged 1 commit intomainfrom
betterErrorHandling
Jun 19, 2025
Merged

Add user-friendly error handling for OpenAI API responses#8
heymaaz merged 1 commit intomainfrom
betterErrorHandling

Conversation

@heymaaz
Copy link
Copy Markdown
Owner

@heymaaz heymaaz commented Jun 19, 2025

  • Introduced a helper function to generate meaningful error messages for users based on specific OpenAI API error codes.
  • Updated the generateAiResponse action to include detailed error messages in the response handling.
  • Modified the schema and related mutations to store and manage error details effectively.
  • Implemented a mechanism in the chat component to display error messages as toast notifications for better user experience.

Summary by CodeRabbit

  • New Features

    • Error messages from the AI chat are now more user-friendly and specific, providing clearer explanations for issues such as invalid API keys, quota limits, or authentication errors.
    • When an error occurs, detailed error information is displayed as a toast notification in the chat interface.
  • Bug Fixes

    • Error toasts are now shown only once per message and reset when switching conversations, preventing duplicate notifications.
  • Improvements

    • Error details are now stored and tracked with each message, enhancing transparency and troubleshooting.

- Introduced a helper function to generate meaningful error messages for users based on specific OpenAI API error codes.
- Updated the `generateAiResponse` action to include detailed error messages in the response handling.
- Modified the schema and related mutations to store and manage error details effectively.
- Implemented a mechanism in the chat component to display error messages as toast notifications for better user experience.
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jun 19, 2025

Walkthrough

A user-friendly error messaging system was implemented for AI chat interactions. Error details are now extracted, stored, and surfaced to users via toasts when AI message generation fails. Schema, mutations, and frontend logic were updated to support and display specific error information per message and conversation.

Changes

File(s) Change Summary
convex/chat.ts Added getUserFriendlyErrorMessage helper; integrated it into error handling in AI response logic.
convex/chatQueriesAndMutations.ts Extended message schema and mutations to accept and store optional errorDetails field.
convex/schema.ts Added optional errorDetails string field to messages table schema.
src/components/chat/useChat.ts Added logic to track and toast new error messages with details per conversation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant Backend
    participant OpenAI/OpenRouter

    User->>Frontend: Sends message
    Frontend->>Backend: generateAiResponse
    Backend->>OpenAI/OpenRouter: Request AI response
    OpenAI/OpenRouter-->>Backend: Response or Error
    alt Success
        Backend->>Backend: Store AI message
        Backend-->>Frontend: Message with content
        Frontend-->>User: Display AI response
    else Error
        Backend->>Backend: Extract user-friendly error message
        Backend->>Backend: Store AI message with errorDetails
        Backend-->>Frontend: Message with error status and details
        Frontend->>Frontend: Toast errorDetails if not already shown
        Frontend-->>User: Display error toast
    end
Loading

Suggested labels

codex

Poem

A hiccup in the AI chat,
Now tells you where the trouble's at!
With error details clear and bright,
Toasts pop up, a helpful sight.
Each message learns from what went wrong,
So chats can hop and bounce along.
🐇✨

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

@netlify
Copy link
Copy Markdown

netlify bot commented Jun 19, 2025

Deploy Preview for t3chatcloneathon ready!

Name Link
🔨 Latest commit b41b444
🔍 Latest deploy log https://app.netlify.com/projects/t3chatcloneathon/deploys/6853ed384db2f1000879fa68
😎 Deploy Preview https://deploy-preview-8--t3chatcloneathon.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@heymaaz heymaaz requested a review from Copilot June 19, 2025 10:58
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR enhances error handling for OpenAI API responses by introducing user-friendly error messages that are both stored and displayed as toast notifications. Key changes include:

  • Adding new state and effects in the chat component to track and display error messages.
  • Updating schema and mutations to store detailed error information.
  • Implementing a helper function to generate meaningful error messages based on specific API error codes.

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
src/components/chat/useChat.ts Added refs and effects to show toast notifications for new error messages.
convex/schema.ts Updated schema to include an optional errorDetails property.
convex/chatQueriesAndMutations.ts Modified mutations to include errorDetails when messaging errors.
convex/chat.ts Introduced a helper function for mapping API errors to user-friendly messages and updated the action accordingly.
Comments suppressed due to low confidence (1)

convex/chat.ts:76

  • Consider verifying whether the check for authentication errors should inspect error.error.code instead of error.code for consistency with the surrounding error handling logic.
      if (error.code === 401 && error.message.includes("No auth credentials")) {

Copy link
Copy Markdown

@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

🧹 Nitpick comments (1)
convex/chat.ts (1)

59-91: Excellent error message standardization with a minor improvement needed.

The getUserFriendlyErrorMessage helper function comprehensively handles various error scenarios and provides meaningful user feedback. However, there's a static analysis suggestion to improve line 63.

Apply this diff to use optional chaining as suggested by static analysis:

-    if (error.error && error.error.message) {
+    if (error.error?.message) {
       const message = error.error.message;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9504d81 and b41b444.

📒 Files selected for processing (4)
  • convex/chat.ts (3 hunks)
  • convex/chatQueriesAndMutations.ts (6 hunks)
  • convex/schema.ts (1 hunks)
  • src/components/chat/useChat.ts (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
convex/chat.ts

[error] 63-63: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (9)
convex/schema.ts (1)

25-25: LGTM! Clean schema enhancement.

The addition of the optional errorDetails field to the messages table is well-designed and aligns perfectly with the error handling improvements.

src/components/chat/useChat.ts (3)

55-56: LGTM! Well-designed state tracking.

The refs for tracking message count and seen error IDs are appropriately used to prevent duplicate toast notifications.


536-553: LGTM! Robust error toast implementation.

The effect correctly monitors for new error messages and displays toasts with specific error details while avoiding duplicates through proper ID tracking.


555-561: LGTM! Proper conversation-scoped cleanup.

The effect appropriately resets the seen error message tracking when switching conversations, ensuring error toasts are managed per conversation context.

convex/chat.ts (2)

770-770: LGTM! Proper error detail integration.

The error detail is appropriately passed to the mutation when no content is generated.


776-776: LGTM! Consistent error handling integration.

The getUserFriendlyErrorMessage helper is properly integrated across all error scenarios, ensuring users receive meaningful feedback regardless of where errors occur.

Also applies to: 791-791, 797-797, 804-804

convex/chatQueriesAndMutations.ts (3)

38-38: LGTM! Consistent validator update.

The messageDoc validator correctly includes the new errorDetails field, maintaining consistency with the schema changes.


356-356: LGTM! Proper mutation enhancement.

The storeAiMessage mutation correctly accepts and stores the errorDetails field, enabling detailed error information to be persisted alongside message status.

Also applies to: 384-384, 407-407


677-677: LGTM! Enhanced error tracking capability.

The markMessageError mutation is properly enhanced to accept and store detailed error information, completing the error handling pipeline.

Also applies to: 682-682, 693-693

@heymaaz heymaaz merged commit 87ba453 into main Jun 19, 2025
6 checks passed
@heymaaz heymaaz deleted the betterErrorHandling branch June 19, 2025 11: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.

2 participants