Skip to content

feat: better error messages #439

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

Merged
merged 5 commits into from
Feb 22, 2025
Merged

feat: better error messages #439

merged 5 commits into from
Feb 22, 2025

Conversation

RohitR311
Copy link
Collaborator

@RohitR311 RohitR311 commented Feb 10, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved error notifications when API key retrieval fails. Users now receive detailed messages that clearly indicate specific issues such as unauthorized access, missing resources, server errors, or connectivity problems instead of seeing a generic error message. This change provides clearer, more actionable feedback for troubleshooting.
  • New Features

    • Enhanced response structure for the API key retrieval endpoint, including standardized error codes and success indicators to improve clarity and consistency in user notifications.
    • Restructured error and success messages for API key management across multiple languages, providing clearer communication regarding the outcomes of user actions.

Copy link

coderabbitai bot commented Feb 10, 2025

Walkthrough

The changes improve error handling in the API key management functionality by categorizing errors based on HTTP status codes in the fetchApiKey, generateApiKey, and deleteApiKey functions. The response structure for authentication routes has been standardized to include specific error codes and success indicators. Additionally, the localization files have been updated to reflect a nested structure for error and success messages, enhancing clarity and specificity in user notifications.

Changes

File Change Summary
src/components/api/ApiKey.tsx Enhanced error handling in fetchApiKey, generateApiKey, and deleteApiKey functions to categorize errors based on status codes (401, 404, 500) and notify users with specific messages. Updated copyToClipboard function to handle copy errors.
server/src/routes/auth.ts Modified response structure for /generate-api-key and /api-key endpoints to include standardized code fields for various errors and an ok field for success responses.
public/locales/de.json Restructured error and success messages for API key management into a nested format under "errors" and "success".
public/locales/en.json Restructured error and success messages for API key management into a nested format under "errors" and "success".
public/locales/es.json Restructured error and success messages for API key management into a nested format under "errors" and "success".
public/locales/ja.json Restructured error and success messages for API key management into a nested format under "errors" and "success".
public/locales/zh.json Restructured error and success messages for API key management into a nested format under "errors" and "success".

Suggested labels

Type: Enhancement, Scope: UI/UX

Suggested reviewers

  • amhsirak

Poem

Oh what a hop, oh what a leap,
I found new code that doesn't sleep.
Error checks so neat and true,
From 401 to 500, they guide you through.
I'm a rabbit, code, and delight in the change,
Hopping on bugs, feeling oh-so estranged!
🐇 Happy coding in every range!


🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 0

🧹 Nitpick comments (1)
src/components/api/ApiKey.tsx (1)

48-72: Good error handling implementation, with some suggestions for improvement.

The error handling is well-structured and provides specific feedback based on different error scenarios. Here are some suggestions to enhance it further:

+const ERROR_KEYS = {
+  401: 'unauthorized',
+  404: 'not_found',
+  429: 'rate_limit',
+  500: 'server',
+} as const;
+
 const fetchApiKey = async () => {
   try {
     const { data } = await axios.get(`${apiUrl}/auth/api-key`);
     setApiKey(data.api_key);
     notify('success', t('apikey.notifications.success.fetch'));
   } catch (error: any) {
     const status = error.response?.status;
-    let errorKey = 'unknown';
-
-    switch (status) {
-      case 401:
-        errorKey = 'unauthorized';
-        break;
-      case 404:
-        errorKey = 'not_found';
-        break;
-      case 500:
-        errorKey = 'server';
-        break;
-      default:
-        if (error.message?.includes('Network Error')) {
-          errorKey = 'network';
-        }
-    }
+    const errorKey = ERROR_KEYS[status] ||
+      (axios.isAxiosError(error) && !error.response ? 'network' : 'unknown');

     notify(
       'error',
       t(`apikey.notifications.errors.fetch.${errorKey}`, {
         error: error.response?.data?.message || error.message
       })
     );

Changes suggested:

  1. Define error keys as constants for better maintainability
  2. Add rate limit (429) handling
  3. Use object literal instead of switch statement
  4. Use axios.isAxiosError for more robust network error detection
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between be7c599 and fcb75f4.

📒 Files selected for processing (1)
  • src/components/api/ApiKey.tsx (1 hunks)
🔇 Additional comments (1)
src/components/api/ApiKey.tsx (1)

46-46: LGTM!

Good addition of success notification to provide immediate feedback to the user.

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

🧹 Nitpick comments (2)
server/src/routes/auth.ts (2)

284-288: Consider adding a success code for consistency.

While the success response includes the ok field, consider adding a code field for consistency with error responses.

 return res.status(200).json({
   ok: true,
+  code: "success",
   message: "API key fetched successfully",
   api_key: user.api_key || null,
 });

264-295: Consider standardizing error responses across all routes.

The improved error handling structure in the /api-key endpoint provides better clarity. Consider applying this pattern to other routes in the file for consistency.

The standardized response structure includes:

  • ok boolean field
  • error message field
  • code for error categorization

Example routes that could benefit from this pattern:

  • /register
  • /login
  • /logout
  • /current-user
  • /user/:id
  • /generate-api-key
  • /delete-api-key
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fcb75f4 and 744778a.

📒 Files selected for processing (1)
  • server/src/routes/auth.ts (2 hunks)
🔇 Additional comments (3)
server/src/routes/auth.ts (3)

264-268: LGTM! Improved unauthorized error response.

The standardized response structure with ok and code fields enhances error handling clarity.


277-281: LGTM! Enhanced user not found error response.

The standardized response structure with ok and code fields improves error handling clarity.


290-295: LGTM! Improved server error response and logging.

The addition of error logging and standardized error response structure enhances debugging capabilities.

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

🧹 Nitpick comments (4)
public/locales/zh.json (1)

143-170: Enhanced Nested Error Structure for API Key Management
The restructured nested error messages (under keys such as "fetch", "generate", "delete", and "copy") now provide a much more granular level of detail for failures (network issues, unauthorized access, not found, server errors, and unknown errors). Please double-check that all function calls in the front end reference these new keys correctly.

public/locales/ja.json (1)

143-170: Improved Error Message Granularity in Japanese Localization
The introduction of a nested error structure that encapsulates distinct error messages for "fetch", "generate", "delete", and "copy" operations improves precision. Please confirm that the error keys match the ones sent by the backend and are handled correctly in the UI.

public/locales/es.json (1)

143-170: Mejora en la estructura anidada de los mensajes de error
La nueva organización de los mensajes de error en categorías ("fetch", "generate", "delete" y "copy") mejora notablemente la claridad del feedback en caso de fallo. Verifique que esta estructura se refleje de forma coherente en los mensajes mostrados al usuario.

public/locales/de.json (1)

142-168: Verbesserte Fehlerstruktur in der deutschen Lokalisierung
Die Umstrukturierung der Fehlermeldungen in verschachtelte Kategorien (unter "fetch", "generate", "delete" und "copy") erleichtert das differenzierte Fehlermanagement. Bitte überprüfen Sie, dass alle API-Antworten diese neuen Schlüssel unterstützen und die front-end Logik entsprechend angepasst wurde.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 744778a and d800158.

📒 Files selected for processing (7)
  • public/locales/de.json (1 hunks)
  • public/locales/en.json (1 hunks)
  • public/locales/es.json (1 hunks)
  • public/locales/ja.json (1 hunks)
  • public/locales/zh.json (1 hunks)
  • server/src/routes/auth.ts (4 hunks)
  • src/components/api/ApiKey.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • server/src/routes/auth.ts
  • src/components/api/ApiKey.tsx
🔇 Additional comments (6)
public/locales/zh.json (1)

172-177: Structured Success Notifications for API Key Operations
The newly added “success” messages clearly distinguish the outcomes for fetching, generating, deleting, and copying API keys. This will help deliver clearer user feedback. No issues noted.

public/locales/ja.json (1)

172-177: Clear Success Feedback
The clear, segmented success messages now distinctly indicate when an API key is successfully retrieved, generated, deleted, or copied. This consistency will lead to improved user feedback across the application.

public/locales/en.json (2)

143-170: Detailed Error Messages Enhancement
The detailed error messages (covering network, unauthorized, not found, server, and unknown errors) now provide extra diagnostic information. This structure is beneficial for both debugging and user support. Please verify that all API endpoints now return error codes matching these keys.


172-177: Success Message Structuring
The success messages for each action are now differentiated and clear, providing explicit end-user feedback after operations. Ensure that any client-side mapping of these responses is updated accordingly.

public/locales/es.json (1)

172-177: Mensajes de éxito bien segmentados
El agregado de mensajes de éxito específicos para cada operación de la clave API ofrece una retroalimentación precisa para el usuario. Todo luce correcto; asegúrese de que la lógica de presentación utilice estos nuevos mensajes.

public/locales/de.json (1)

171-176: Klare Erfolgsmeldungen für API-Schlüssel-Operationen
Die neuen Erfolgsmeldungen liefern präzise Rückmeldungen (für das Abrufen, Generieren, Löschen und Kopieren von API-Schlüsseln), was die Benutzerfreundlichkeit erhöht.

@amhsirak amhsirak added the Type: Enhancement Improvements to existing features label Feb 12, 2025
@RohitR311
Copy link
Collaborator Author

@amhsirak Review

@amhsirak amhsirak merged commit 4d3594e into develop Feb 22, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: Enhancement Improvements to existing features
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants