Skip to content

Comments

feat: add error handling and localization for key loading failures#365

Merged
ding113 merged 2 commits intodevfrom
fix/better-error-display
Dec 19, 2025
Merged

feat: add error handling and localization for key loading failures#365
ding113 merged 2 commits intodevfrom
fix/better-error-display

Conversation

@ding113
Copy link
Owner

@ding113 ding113 commented Dec 18, 2025

Summary

Enhances error handling and user experience by improving the global error component to differentiate between network errors and general errors, adding proper error catching in forms and data-loading components, and introducing new utility functions for safe error handling.

Problem

When certain errors occurred (particularly network errors like "Failed to fetch"), the application displayed a full-screen error page with raw error messages, which:

  1. Disrupted user workflow with an intrusive full-screen error
  2. Exposed raw error messages that could contain sensitive information
  3. Did not provide actionable guidance for network-related issues

Related Issues:

Solution

Approach

  1. Network Error Detection: New utility function isNetworkError() identifies network-related errors (fetch failures, timeouts, connection refused, etc.)
  2. Enhanced Global Error Component: Differentiates between network errors and general errors, showing specific guidance for network issues
  3. Form Error Handling: Added try-catch blocks with proper error logging to prevent unhandled promise rejections from triggering the global error boundary
  4. Server Action Hook: New useServerAction hook provides standardized error handling with toast notifications instead of full-screen errors

Changes

Core Changes

  • src/app/global-error.tsx - Enhanced to detect network errors and show appropriate UI with troubleshooting steps
  • src/lib/utils/error-detection.ts - New utility for network error detection and safe error message handling
  • src/lib/hooks/use-server-action.ts - New hook for unified server action execution with error handling

Form Error Handling

  • src/app/[locale]/dashboard/_components/user/forms/add-key-form.tsx - Added error handling for provider group loading
  • src/app/[locale]/dashboard/_components/user/forms/edit-key-form.tsx - Added error handling for provider group loading
  • src/app/[locale]/dashboard/_components/user/forms/user-form.tsx - Added error handling for provider group loading
  • src/app/[locale]/dashboard/logs/_components/usage-logs-filters.tsx - Added error handling for key loading with toast notification
  • src/app/[locale]/settings/providers/_components/forms/api-test-button.tsx - Added error handling for preset loading
  • src/app/[locale]/settings/providers/_components/provider-rich-list-item.tsx - Added error handling for key retrieval

Localization

  • Added loadKeysFailed error message in 5 languages:
    • English: "Failed to load keys"
    • Japanese: "キーリストの読み込みに失敗しました"
    • Russian: "Не удалось загрузить список ключей"
    • Simplified Chinese: "加载密钥列表失败"
    • Traditional Chinese: "載入密鑰列表失敗"

Breaking Changes

None. All changes are additive and backward-compatible.

Testing

Manual Testing

  1. Disconnect network and navigate to any form page
  2. Verify the global error page shows "Network Connection Error" with troubleshooting steps
  3. Reconnect and verify "Try again" button works
  4. Test the "Go to Home" button navigates correctly
  5. On forms, simulate network failure during provider group loading - verify console error logged without full-screen crash
  6. Test key loading failure on logs page - verify toast notification appears

Security Considerations

  • Raw error messages are never exposed to users (could contain DB strings, file paths, internal APIs)
  • Error digest IDs are still shown for debugging purposes
  • All user-facing messages are predefined/localized strings

Checklist

  • Code follows project conventions
  • Self-review completed
  • Tests pass locally
  • Localization added for all 5 supported languages

Description enhanced by Claude AI

- Added new error message for failed key loading in multiple languages (English, Japanese, Russian, Simplified Chinese, Traditional Chinese).
- Enhanced global error component to differentiate between network errors and general errors, providing specific guidance for network issues.
- Updated forms to include error handling for provider group loading and key retrieval, improving user feedback on failures.
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @ding113, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the application's error handling capabilities and user experience by introducing more specific and localized error messages, particularly for key loading failures. It refines the global error display to offer distinct guidance for network connectivity problems versus general errors and integrates robust error management into critical forms. Furthermore, it establishes a standardized pattern for handling server action errors across the application, ensuring consistency and improved feedback.

Highlights

  • Localized Error Messages: Introduced a new, specific error message for key loading failures, localized across English, Japanese, Russian, Simplified Chinese, and Traditional Chinese.
  • Enhanced Global Error Handling: The global error component now intelligently distinguishes between network-related errors and general application errors, providing users with tailored guidance and troubleshooting steps for network issues.
  • Improved Form Error Feedback: Error handling has been integrated into various forms, specifically for provider group loading and key retrieval, ensuring better user feedback when these operations fail.
  • Standardized Server Action Error Management: A new useServerAction hook and withErrorHandling utility have been added to provide a consistent approach to managing loading states, catching network errors, and displaying toast notifications for server actions.
  • Error Detection Utility: A new utility file error-detection.ts was created to centralize logic for identifying network errors and providing safe, user-friendly error messages, preventing sensitive information leakage.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@github-actions github-actions bot added enhancement New feature or request area:UI area:i18n size/M Medium PR (< 500 lines) labels Dec 18, 2025
@github-actions
Copy link
Contributor

🧪 测试结果

测试类型 状态
代码质量
单元测试
集成测试
API 测试

总体结果: ✅ 所有测试通过

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request significantly improves error handling across the application by introducing a global error boundary, a centralized server action hook, and more robust error catching in several components. The changes are well-structured and enhance both user feedback and application stability. My review includes a few suggestions to further improve error handling by providing user-facing feedback in forms where it's currently missing and ensuring all failure paths from server actions are properly handled.

Comment on lines +44 to +46
loadGroups.then(setProviderGroupSuggestions).catch((err) => {
console.error("[AddKeyForm] Failed to load provider groups:", err);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The error handling for loading provider groups only logs to the console. This provides no feedback to the user, who might be confused about why suggestions aren't appearing. It would be better to show a toast notification to inform the user about the failure. You can use a generic error message from your translation files, for example dashboard.error.loadFailed.

    loadGroups.then(setProviderGroupSuggestions).catch((err) => {
      console.error("[AddKeyForm] Failed to load provider groups:", err);
      toast.error("Failed to load provider groups. Please try again.");
    });

Comment on lines +59 to +61
loadGroups.then(setProviderGroupSuggestions).catch((err) => {
console.error("[EditKeyForm] Failed to load provider groups:", err);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The error handling for loading provider groups only logs to the console. This provides no feedback to the user, who might be confused about why suggestions aren't appearing. It would be better to show a toast notification to inform the user about the failure. You can use a generic error message from your translation files, for example dashboard.error.loadFailed.

    loadGroups.then(setProviderGroupSuggestions).catch((err) => {
      console.error("[EditKeyForm] Failed to load provider groups:", err);
      toast.error("Failed to load provider groups. Please try again.");
    });

Comment on lines +81 to +83
.catch((err) => {
console.error("[UserForm] Failed to load provider groups:", err);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The error handling for loading provider groups only logs to the console. This provides no feedback to the user, who might be confused about why suggestions aren't appearing. It would be better to show a toast notification to inform the user about the failure. You can use a generic error message from your translation files, for example dashboard.error.loadFailed.

      .catch((err) => {
        console.error("[UserForm] Failed to load provider groups:", err);
        toast.error("Failed to load provider groups. Please try again.");
      });

Comment on lines +117 to +119
if (keysResult.ok && keysResult.data) {
setKeys(keysResult.data);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The current implementation handles exceptions when calling getKeys, but it doesn't handle the case where the server action returns a failure ({ ok: false, error: '...' }). This can lead to silent failures where the key list fails to load without any user notification.

        if (keysResult.ok && keysResult.data) {
          setKeys(keysResult.data);
        } else if (!keysResult.ok) {
          console.error("Failed to load keys:", keysResult.error);
          toast.error(t("logs.error.loadKeysFailed"));
        }

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Code Review Summary

Overall this is a well-structured PR that adds proper error handling and localization for key loading failures. The changes improve user experience by catching and logging errors that were previously unhandled.

PR Size: M

  • Lines changed: 446 (390 additions + 56 deletions)
  • Files changed: 14

Issues Found

Category Critical High Medium Low
Logic/Bugs 0 0 1 0
Security 0 0 0 0
Error Handling 0 0 0 0
Types 0 0 0 0
Comments/Docs 0 0 0 0
Tests 0 0 0 0
Simplification 0 0 0 0

Medium Priority Issues (Should Fix)

1. src/app/global-error.tsx:67 - Button container not centered properly

The button container uses display: "flex" with gap: "12px", but the parent container only has textAlign: "center". Text alignment does not center flex children - you need justifyContent: "center" on the flex container to center the buttons horizontally.

Suggested fix:

<div style={{ display: "flex", gap: "12px", justifyContent: "center" }}>

Review Coverage

  • Logic and correctness
  • Security (OWASP Top 10)
  • Error handling - Well done: errors are now logged and user feedback is provided
  • Type safety
  • Documentation accuracy
  • Test coverage - Note: New utility files (use-server-action.ts, error-detection.ts) are not being used yet in this PR, suggesting they may be infrastructure for future work
  • Code clarity

Additional Notes

  1. The new useServerAction hook and withErrorHandling utility in src/lib/hooks/use-server-action.ts are well-designed but are not used by any component in this PR. Consider either using them to replace the manual .catch() patterns added in this PR, or moving them to a separate PR.

  2. The getSafeErrorMessage function in error-detection.ts always returns the fallback message and ignores the error parameter (intentionally for security). The function signature is clean but the parameter is unused - this is intentional per the security comment.

  3. The error handling improvements in the form components (add-key-form.tsx, edit-key-form.tsx, user-form.tsx, etc.) consistently log errors with console.error and provide user feedback via toast - this is good practice.


Automated review by Claude AI

…-button.tsx

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@ding113 ding113 added this to the v0.3.31 milestone Dec 18, 2025
@ding113 ding113 merged commit 054ed68 into dev Dec 19, 2025
6 of 8 checks passed
@github-project-automation github-project-automation bot moved this from Backlog to Done in Claude Code Hub Roadmap Dec 19, 2025
@github-actions github-actions bot mentioned this pull request Dec 19, 2025
12 tasks
@ding113 ding113 deleted the fix/better-error-display branch December 23, 2025 17:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:i18n area:UI enhancement New feature or request size/M Medium PR (< 500 lines)

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant