Skip to content

Conversation

@nileshpahari
Copy link
Contributor

Proposed change

Correct the syntax of the Error constructor, in order to preserve the original error.

Files modified

frontend/src/app/api/auth/[...nextauth]/route.ts
frontend/src/components/ModuleForm.tsx

Resolves #2803

Checklist

  • I've read and followed the contributing guidelines.
  • I've run make check-test locally; all checks and tests passed.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 7, 2025

Summary by CodeRabbit

  • Refactor
    • Standardized error message formatting across authentication flows to produce clearer, user-facing messages.
    • Adjusted form component error handling to surface formatted errors in the UI instead of throwing, improving consistency in reporting.

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Updated error handling in two frontend files: frontend/src/app/api/auth/[...nextauth]/route.ts now interpolates caught errors into single-string Error messages; frontend/src/components/ModuleForm.tsx builds a formatted errorMessage and calls setError(...) instead of constructing a multi-argument Error. No public API or signature changes.

Changes

Cohort / File(s) Summary
Auth route error formatting
frontend/src/app/api/auth/[...nextauth]/route.ts
Replaced two-argument new Error(..., err) usages with a single-string template literal that embeds the caught err (e.g., Failed to ...: ${err}). Control flow (re-throw) and return behavior unchanged.
ModuleForm error handling
frontend/src/components/ModuleForm.tsx
Catch block changed: it computes a robust errorMessage (handles Error, string, fallback) and calls setError(errorMessage) instead of throw new Error(..., err). Success/data paths unchanged.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Verify any code or monitoring that expected exceptions is not relying on thrown Errors from these locations.
  • Confirm setError updates UI/state correctly and no callers depend on exception propagation.
  • Check interpolated error content for accidental exposure of sensitive information.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: fixing incorrect Error constructor syntax across the affected files.
Description check ✅ Passed The description clearly relates to the changeset, explaining the proposed change to correct Error constructor syntax and listing the modified files.
Linked Issues check ✅ Passed The PR successfully addresses issue #2803 by correcting Error constructor syntax in both specified files (route.ts and ModuleForm.tsx) with template strings embedding error messages.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing Error constructor syntax in the two specified files; no unrelated modifications are present.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

♻️ Duplicate comments (1)
frontend/src/app/api/auth/[...nextauth]/route.ts (1)

34-36: Error constructor syntax is now correct.

Same fix and recommendations as the checkIfProjectLeader function above. Consider applying consistent error handling improvements to both functions.

🧹 Nitpick comments (1)
frontend/src/app/api/auth/[...nextauth]/route.ts (1)

20-22: Error constructor syntax is now correct.

The fix properly consolidates the error message into a single string parameter. However, consider these improvements:

  1. Use error cause chaining (ES2022) to preserve the original error stack:
throw new Error('Failed to fetch project leader status', { cause: err })
  1. If err is an Error object, extract its message:
throw new Error(`Failed to fetch project leader status: ${err instanceof Error ? err.message : String(err)}`)
  1. Since this function is called during JWT callback (line 78) without visible error handling, consider whether re-throwing is appropriate or if the auth flow should degrade gracefully.
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 78cf54a and 6217a9b.

📒 Files selected for processing (2)
  • frontend/src/app/api/auth/[...nextauth]/route.ts (2 hunks)
  • frontend/src/components/ModuleForm.tsx (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-07-12T17:14:28.536Z
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/mentorship/programs/[programKey]/edit/page.tsx:90-128
Timestamp: 2025-07-12T17:14:28.536Z
Learning: Both ProgramForm (programCard.tsx) and ModuleForm (mainmoduleCard.tsx) components already implement HTML validation using the `required` attribute on form fields. The browser's native validation prevents form submission and displays error messages when required fields are empty, eliminating the need for additional JavaScript validation before GraphQL mutations.

Applied to files:

  • frontend/src/components/ModuleForm.tsx

@nileshpahari nileshpahari force-pushed the fix/incorrect-error-constructor-usage-2803 branch from cf43342 to 7bcb563 Compare December 7, 2025 21:16
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: 0

🧹 Nitpick comments (1)
frontend/src/components/ModuleForm.tsx (1)

286-290: Good: use setError instead of throwing; consider a better fallback for non-Error values

Switching from throwing to setError fixes the unhandled rejection and correctly surfaces failures in the UI while still clearing results and hiding suggestions. One small improvement: for non-Error values, the message currently ends with an empty suffix; you could preserve more context or at least show a generic fallback, e.g.:

setError(
  `Error fetching suggestions: ${
    err instanceof Error ? err.message : String(err || 'Unknown error')
  }`
)
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6217a9b and 7bcb563.

📒 Files selected for processing (2)
  • frontend/src/app/api/auth/[...nextauth]/route.ts (2 hunks)
  • frontend/src/components/ModuleForm.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/app/api/auth/[...nextauth]/route.ts
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/mentorship/programs/[programKey]/edit/page.tsx:90-128
Timestamp: 2025-07-12T17:14:28.536Z
Learning: Both ProgramForm (programCard.tsx) and ModuleForm (mainmoduleCard.tsx) components already implement HTML validation using the `required` attribute on form fields. The browser's native validation prevents form submission and displays error messages when required fields are empty, eliminating the need for additional JavaScript validation before GraphQL mutations.
📚 Learning: 2025-07-12T17:14:28.536Z
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/mentorship/programs/[programKey]/edit/page.tsx:90-128
Timestamp: 2025-07-12T17:14:28.536Z
Learning: Both ProgramForm (programCard.tsx) and ModuleForm (mainmoduleCard.tsx) components already implement HTML validation using the `required` attribute on form fields. The browser's native validation prevents form submission and displays error messages when required fields are empty, eliminating the need for additional JavaScript validation before GraphQL mutations.

Applied to files:

  • frontend/src/components/ModuleForm.tsx

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

🧹 Nitpick comments (1)
frontend/src/components/ModuleForm.tsx (1)

289-295: Error handling is solid; consider simplifying nested ternary for readability

The new error handling correctly derives a user-facing message from different err types and surfaces it via setError, which is a good improvement over throwing. The nested ternary, though, is a bit hard to scan (and was flagged by Sonar); an if / else if / else chain would be clearer.

You could refactor like this:

-        const errorMessage =
-          err instanceof Error
-            ? err.message
-            : typeof err === 'string'
-              ? err
-              : 'An unexpected error occurred'
-        setError(`Error fetching suggestions: ${errorMessage}`)
+        let errorMessage: string
+
+        if (err instanceof Error) {
+          errorMessage = err.message
+        } else if (typeof err === 'string') {
+          errorMessage = err
+        } else {
+          errorMessage = 'An unexpected error occurred'
+        }
+
+        setError(`Error fetching suggestions: ${errorMessage}`)
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7bcb563 and 1fade10.

📒 Files selected for processing (1)
  • frontend/src/components/ModuleForm.tsx (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/api/auth/[...nextauth]/route.ts:13-25
Timestamp: 2025-08-10T11:08:47.258Z
Learning: In the OWASP Nest codebase (frontend/src/app/api/auth/[...nextauth]/route.ts), input validation and string trimming for authentication-related queries like `isProjectLeader` and `isMentor` are handled in the backend rather than the frontend. The backend is responsible for sanitizing and validating input parameters.
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/mentorship/programs/[programKey]/edit/page.tsx:90-128
Timestamp: 2025-07-12T17:14:28.536Z
Learning: Both ProgramForm (programCard.tsx) and ModuleForm (mainmoduleCard.tsx) components already implement HTML validation using the `required` attribute on form fields. The browser's native validation prevents form submission and displays error messages when required fields are empty, eliminating the need for additional JavaScript validation before GraphQL mutations.
📚 Learning: 2025-07-12T17:14:28.536Z
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/mentorship/programs/[programKey]/edit/page.tsx:90-128
Timestamp: 2025-07-12T17:14:28.536Z
Learning: Both ProgramForm (programCard.tsx) and ModuleForm (mainmoduleCard.tsx) components already implement HTML validation using the `required` attribute on form fields. The browser's native validation prevents form submission and displays error messages when required fields are empty, eliminating the need for additional JavaScript validation before GraphQL mutations.

Applied to files:

  • frontend/src/components/ModuleForm.tsx
🪛 GitHub Check: SonarCloud Code Analysis
frontend/src/components/ModuleForm.tsx

[warning] 292-294: Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=OWASP_Nest&issues=AZr6uj6rki_2q7OKSyPX&open=AZr6uj6rki_2q7OKSyPX&pullRequest=2824

@nileshpahari nileshpahari force-pushed the fix/incorrect-error-constructor-usage-2803 branch from 1fade10 to bed93a6 Compare December 7, 2025 22:27
Copy link
Collaborator

@arkid15r arkid15r left a comment

Choose a reason for hiding this comment

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

Screenshot 2025-12-10 at 6 41 41 PM

I don't think you did.

@arkid15r arkid15r marked this pull request as draft December 11, 2025 02:43
@github-actions github-actions bot added docs Improvements or additions to documentation backend frontend-tests makefile ci labels Dec 11, 2025
@nileshpahari nileshpahari force-pushed the fix/incorrect-error-constructor-usage-2803 branch from addedb9 to 78ff559 Compare December 11, 2025 07:37
@github-actions github-actions bot removed docs Improvements or additions to documentation backend frontend-tests makefile ci labels Dec 11, 2025
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: 0

🧹 Nitpick comments (1)
frontend/src/app/api/auth/[...nextauth]/route.ts (1)

20-36: Error construction now correct; optional refinement to include cleaner message.

The new throw new Error(\Failed to fetch ... status Error: ${err}`)calls in both helpers fix the original bug:Error` is now constructed with a single message string that includes the underlying error, so it’s no longer silently discarded.

If you want slightly clearer messages (and to avoid cases like Error: [object Object]), you could optionally tighten this to:

throw new Error(
  `Failed to fetch project leader status: ${
    err instanceof Error ? err.message : String(err)
  }`
)

and similarly for the mentor status path. Not required for correctness, but a bit more robust.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bed93a6 and 78ff559.

📒 Files selected for processing (2)
  • frontend/src/app/api/auth/[...nextauth]/route.ts (2 hunks)
  • frontend/src/components/ModuleForm.tsx (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/api/auth/[...nextauth]/route.ts:13-25
Timestamp: 2025-08-10T11:08:47.258Z
Learning: In the OWASP Nest codebase (frontend/src/app/api/auth/[...nextauth]/route.ts), input validation and string trimming for authentication-related queries like `isProjectLeader` and `isMentor` are handled in the backend rather than the frontend. The backend is responsible for sanitizing and validating input parameters.
📚 Learning: 2025-08-10T11:08:47.258Z
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/api/auth/[...nextauth]/route.ts:13-25
Timestamp: 2025-08-10T11:08:47.258Z
Learning: In the OWASP Nest codebase (frontend/src/app/api/auth/[...nextauth]/route.ts), input validation and string trimming for authentication-related queries like `isProjectLeader` and `isMentor` are handled in the backend rather than the frontend. The backend is responsible for sanitizing and validating input parameters.

Applied to files:

  • frontend/src/app/api/auth/[...nextauth]/route.ts
📚 Learning: 2025-07-12T17:14:28.536Z
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/mentorship/programs/[programKey]/edit/page.tsx:90-128
Timestamp: 2025-07-12T17:14:28.536Z
Learning: Both ProgramForm (programCard.tsx) and ModuleForm (mainmoduleCard.tsx) components already implement HTML validation using the `required` attribute on form fields. The browser's native validation prevents form submission and displays error messages when required fields are empty, eliminating the need for additional JavaScript validation before GraphQL mutations.

Applied to files:

  • frontend/src/components/ModuleForm.tsx
🔇 Additional comments (1)
frontend/src/components/ModuleForm.tsx (1)

286-291: Good fix: surface fetch errors via state instead of throwing.

Using setError in the catch block (while still clearing results and hiding suggestions) correctly avoids the previous unhandled promise rejection from useEffect and routes failures into the existing UI error message. This matches the PR objective without changing success-path behavior.

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 11, 2025
@nileshpahari
Copy link
Contributor Author

Sorry about that, @arkid15r . While addressing CodeRabbit’s suggestions, I copy-pasted them quickly and didn’t run the checks afterward. I’ve fixed the issue now, and it won’t happen again. Please take a look when you can

@nileshpahari nileshpahari marked this pull request as ready for review December 11, 2025 07:47
@sonarqubecloud
Copy link

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

♻️ Duplicate comments (1)
frontend/src/app/api/auth/[...nextauth]/route.ts (1)

37-39: Same error-handling pattern as above — looks good

This catch block mirrors the updated pattern in checkIfProjectLeader, so the bug is consistently fixed here as well. No additional changes needed beyond any optional refactor you decide to apply to both.

🧹 Nitpick comments (1)
frontend/src/app/api/auth/[...nextauth]/route.ts (1)

21-23: Error construction fix is correct; optional small reuse/refactor

Using a single-string Error message and explicitly embedding err.message (with a sane fallback) correctly fixes the original bug and keeps the thrown error informative. This is good as-is.

If you want to DRY things up later, you could extract a tiny helper like toStatusError(context: string, err: unknown) and reuse it in both checkIfProjectLeader and checkIfMentor, but that’s strictly optional. Based on learnings, no additional input validation is needed here because it’s handled on the backend.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 78ff559 and c835613.

📒 Files selected for processing (1)
  • frontend/src/app/api/auth/[...nextauth]/route.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/api/auth/[...nextauth]/route.ts:13-25
Timestamp: 2025-08-10T11:08:47.258Z
Learning: In the OWASP Nest codebase (frontend/src/app/api/auth/[...nextauth]/route.ts), input validation and string trimming for authentication-related queries like `isProjectLeader` and `isMentor` are handled in the backend rather than the frontend. The backend is responsible for sanitizing and validating input parameters.
📚 Learning: 2025-08-10T11:08:47.258Z
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/api/auth/[...nextauth]/route.ts:13-25
Timestamp: 2025-08-10T11:08:47.258Z
Learning: In the OWASP Nest codebase (frontend/src/app/api/auth/[...nextauth]/route.ts), input validation and string trimming for authentication-related queries like `isProjectLeader` and `isMentor` are handled in the backend rather than the frontend. The backend is responsible for sanitizing and validating input parameters.

Applied to files:

  • frontend/src/app/api/auth/[...nextauth]/route.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Incorrect Error Constructor Usage

2 participants