Skip to content

fix: default to standard text error#3913

Merged
chronark merged 1 commit intomainfrom
eng-1742-improve-error-response-for-root-key-creation-failure
Sep 9, 2025
Merged

fix: default to standard text error#3913
chronark merged 1 commit intomainfrom
eng-1742-improve-error-response-for-root-key-creation-failure

Conversation

@MichaelUnkey
Copy link
Collaborator

@MichaelUnkey MichaelUnkey commented Sep 3, 2025

What does this PR do?

Fixes # (issue)
ENG-1742

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • This error should never be seen due to button being disabled if no permissions.
  • Creating root key should still work

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling when creating root keys: users now see a clear message if no permissions are selected (“You need to add at least one permission.”); other failures show a generic retry message.
    • Provides more consistent feedback in the root key dialog during submission.
    • No changes to workflow or data; only messaging updated for clarity.

@linear
Copy link

linear bot commented Sep 3, 2025

@changeset-bot
Copy link

changeset-bot bot commented Sep 3, 2025

⚠️ No Changeset found

Latest commit: 05b41b0

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

@vercel
Copy link

vercel bot commented Sep 3, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
dashboard Ready Ready Preview Comment Sep 3, 2025 8:02pm
engineering Ready Ready Preview Comment Sep 3, 2025 8:02pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 3, 2025

📝 Walkthrough

Walkthrough

Updated the TRPC mutation error handler in use-root-key-dialog.ts to switch from a typed error message display to conditional handling based on err.data?.code, specifically showing a BAD_REQUEST-specific message and a generic fallback.

Changes

Cohort / File(s) Summary
Root key dialog error handling
apps/dashboard/app/(app)/settings/root-keys/components/root-key/hooks/use-root-key-dialog.ts
Changed trpc.rootKey.create.useMutation onError signature from onError(err: { message: string }) to onError(err). Implemented conditional error messaging: if err.data?.code === "BAD_REQUEST" show permission message; otherwise show generic error.

Sequence Diagram(s)

sequenceDiagram
  participant U as User
  participant D as RootKeyDialog
  participant S as TRPC rootKey.create

  U->>D: Submit create root key
  D->>S: mutate(data)
  alt Success
    S-->>D: result
    D-->>U: Close dialog / success UI
  else Error
    S-->>D: err
    alt err.data?.code == "BAD_REQUEST"
      Note over D: Show "You need to add at least one permission."
    else Other error
      Note over D: Show "Something went wrong. Please try again."
    end
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • mcstepp
  • chronark
  • ogzhanolguncu
  • perkinsjr
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch eng-1742-improve-error-response-for-root-key-creation-failure

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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
Copy link
Contributor

github-actions bot commented Sep 3, 2025

Thank you for following the naming conventions for pull request titles! 🙏

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
apps/dashboard/app/(app)/settings/root-keys/components/root-key/hooks/use-root-key-dialog.ts (3)

160-165: Add a local guard to prevent invalid create calls (defense-in-depth).

UI disables the button, but add a runtime check to avoid server roundtrips if the action is triggered programmatically.

   } else {
     // Create new key
-    key.mutate({
+    if (selectedPermissions.length === 0) {
+      toast.error("You need to add at least one permission.");
+      return;
+    }
+    key.mutate({
       name: name && name.length > 0 ? name : undefined,
       permissions: selectedPermissions,
     });
   }

103-106: Avoid exposing raw server error messages in updateName.

For consistency with the create flow and to prevent leaking internal error text, switch to code-based handling (or reuse a shared error handler).

-    onError(err: { message: string }) {
-      toast.error(err.message);
-    },
+    onError(err: unknown) {
+      if (err instanceof (await import("@trpc/client")).TRPCClientError) {
+        switch (err.data?.code) {
+          case "FORBIDDEN":
+          case "UNAUTHORIZED":
+            toast.error("You don’t have permission to update this key.");
+            break;
+          default:
+            toast.error("Something went wrong. Please try again.");
+        }
+      } else {
+        toast.error("Something went wrong. Please try again.");
+      }
+    },

114-116: Unify error handling in updatePermissions with the new pattern.

Same rationale as above; keep error UX consistent across mutations.

-    onError(err: { message: string }) {
-      toast.error(err.message);
-    },
+    onError(err: unknown) {
+      if (err instanceof (await import("@trpc/client")).TRPCClientError) {
+        switch (err.data?.code) {
+          case "FORBIDDEN":
+          case "UNAUTHORIZED":
+            toast.error("You don’t have permission to update permissions.");
+            break;
+          default:
+            toast.error("Something went wrong. Please try again.");
+        }
+      } else {
+        toast.error("Something went wrong. Please try again.");
+      }
+    },
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f4183e2 and 05b41b0.

📒 Files selected for processing (1)
  • apps/dashboard/app/(app)/settings/root-keys/components/root-key/hooks/use-root-key-dialog.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Go API Local / Test
  • GitHub Check: Build / Build
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
apps/dashboard/app/(app)/settings/root-keys/components/root-key/hooks/use-root-key-dialog.ts (1)

196-200: Button enablement logic matches PR intent.

Enabling create only when there are permissions aligns with “don’t show the standard text error by default.”

Comment on lines +89 to 95
onError(err) {
if (err.data?.code === "BAD_REQUEST") {
toast.error("You need to add at least one permission.");
} else {
toast.error("Something went wrong. Please try again.");
}
},
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

⚠️ Potential issue

Type the TRPC error and handle known codes explicitly (avoid implicit any and improve UX).

onError(err) is untyped and relies on .data?.code existing. Tighten types and provide explicit handling for common codes to prevent accidental message leakage and improve clarity.

@@
-  const key = trpc.rootKey.create.useMutation({
+  const key = trpc.rootKey.create.useMutation({
     onSuccess() {
       toast.success(ROOT_KEY_MESSAGES.SUCCESS.ROOT_KEY_GENERATED);
       trpcUtils.settings.rootKeys.query.invalidate();
     },
-    onError(err) {
-      if (err.data?.code === "BAD_REQUEST") {
-        toast.error("You need to add at least one permission.");
-      } else {
-        toast.error("Something went wrong. Please try again.");
-      }
-    },
+    onError(err: unknown) {
+      // Avoid showing raw server messages; branch on safe, known codes only.
+      if (err instanceof (await import("@trpc/client")).TRPCClientError) {
+        switch (err.data?.code) {
+          case "BAD_REQUEST":
+            toast.error("You need to add at least one permission.");
+            break;
+          case "FORBIDDEN":
+          case "UNAUTHORIZED":
+            toast.error("You don’t have permission to create a root key.");
+            break;
+          default:
+            toast.error("Something went wrong. Please try again.");
+        }
+      } else {
+        toast.error("Something went wrong. Please try again.");
+      }
+    },
   });

Committable suggestion skipped: line range outside the PR's diff.

@chronark chronark merged commit 4ba7760 into main Sep 9, 2025
19 checks passed
@chronark chronark deleted the eng-1742-improve-error-response-for-root-key-creation-failure branch September 9, 2025 06:19
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