Skip to content
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

fix(skilavottord): Improve error handling when creating access and companies #16559

Conversation

birkirkristmunds
Copy link
Member

@birkirkristmunds birkirkristmunds commented Oct 25, 2024

TS-931
Attach a link to issue if relevant

What

Improve the error handling when registering access and recycling companies

Why

Prevent showing the user Unhandled Runtime Error in the UI

Screenshots / Gifs

image

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for access control and recycling partner creation, suppressing redundant error messages while informing users through toast notifications.
    • Added checks to prevent duplicate access control entries based on national ID.
    • Improved clarity of error messages for recycling partner creation by including specific company IDs in conflicts.
  • Bug Fixes

    • Improved clarity of error messages related to missing partner IDs in access control creation.

@birkirkristmunds birkirkristmunds requested a review from a team as a code owner October 25, 2024 09:05
Copy link
Contributor

coderabbitai bot commented Oct 25, 2024

Walkthrough

The changes in this pull request enhance error handling for GraphQL mutations related to access control and recycling partner management. Specifically, onError callbacks were added to the createSkilavottordAccessControl and createSkilavottordRecyclingPartner mutations to suppress runtime error messages, as errors are communicated through toast notifications. Additionally, the AccessControlResolver was updated to include a ConflictException for handling duplicate access control entries based on national ID. The overall control flow remains largely unchanged.

Changes

File Change Summary
apps/skilavottord/web/screens/AccessControl/AccessControl.tsx Added onError callback to createSkilavottordAccessControl and updateSkilavottordAccessControl mutations to suppress runtime error messages.
apps/skilavottord/web/screens/RecyclingCompanies/RecyclingCompanyCreate/RecyclingCompanyCreate.tsx Added onError callback to createSkilavottordRecyclingPartner mutation to suppress runtime error messages.
apps/skilavottord/ws/src/app/modules/accessControl/accessControl.resolver.ts Added ConflictException for duplicate entries in createSkilavottordAccessControl mutation; improved error message clarity in verifyRecyclingCompanyInput.
apps/skilavottord/ws/src/app/modules/recyclingPartner/recyclingPartner.resolver.ts Updated error message in createSkilavottordRecyclingPartner mutation for clarity regarding existing partner IDs.

Possibly related PRs

  • fix: init #15975: This PR introduces an error handling mechanism in the createSkilavottordRecyclingPartner mutation, similar to the error handling added for the createSkilavottordAccessControl mutation in the main PR.
  • fix(skilavottord): Error when trying to view and save recycling companies #16159: This PR addresses issues related to the viewing and saving of recycling companies, which involves the RecyclingCompanyUpdate component that is also relevant to the error handling changes in the main PR related to access control management.

Suggested labels

automerge

Suggested reviewers

  • veronikasif
  • thorkellmani

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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.

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

🧹 Outside diff range and nitpick comments (4)
apps/skilavottord/ws/src/app/modules/accessControl/accessControl.resolver.ts (1)

84-90: Good addition of duplicate check, but consider some improvements.

The duplicate check effectively prevents "Unhandled Runtime Error" messages and improves user experience. However, consider these enhancements:

  1. Make the error message more specific by including the nationalId
  2. Add logging for tracking duplicate attempts
  3. Move the duplicate check to the service layer for better separation of concerns

Consider this improvement:

-    const access = await this.accessControlService.findOne(input.nationalId)
-
-    if (access) {
-      throw new ConflictException('Access with that national id already exists')
-    }
-
-    return this.accessControlService.createAccess(input)
+    return this.accessControlService.createAccess(input, {
+      logger: this.logger,
+      errorMessage: `Access already exists for national ID: ${input.nationalId}`,
+    })

Then in the service:

async createAccess(
  input: CreateAccessControlInput,
  options?: { logger?: Logger; errorMessage?: string },
): Promise<AccessControlModel> {
  const existing = await this.findOne(input.nationalId);
  
  if (existing) {
    options?.logger?.warn('Duplicate access creation attempted', {
      nationalId: input.nationalId,
    });
    throw new ConflictException(
      options?.errorMessage ?? 'Access with that national id already exists',
    );
  }
  
  return this.create(input);
}
apps/skilavottord/web/screens/RecyclingCompanies/RecyclingCompanyCreate/RecyclingCompanyCreate.tsx (1)

Line range hint 89-99: Consider centralizing error handling logic.

The error handling is currently split between the mutation's onError callback and the submission handler. Consider consolidating this for better maintainability.

Suggestion:

 const handleCreateRecyclingPartner = handleSubmit(async (input) => {
-    const { errors } = await createSkilavottordRecyclingPartner({
-      variables: { input: { ...input, active: !!input.active } },
-    })
-    if (!errors) {
-      router.push(routes.recyclingCompanies.baseRoute).then(() => {
-        toast.success(t.recyclingCompany.add.added)
-      })
-    }
+    try {
+      const { errors } = await createSkilavottordRecyclingPartner({
+        variables: { input: { ...input, active: !!input.active } },
+      })
+      if (errors?.length) {
+        toast.error(t.recyclingCompany.add.error)
+        return
+      }
+      await router.push(routes.recyclingCompanies.baseRoute)
+      toast.success(t.recyclingCompany.add.added)
+    } catch (error) {
+      console.error('Failed to create recycling partner:', error)
+      toast.error(t.recyclingCompany.add.error)
+    }
 })
apps/skilavottord/web/screens/AccessControl/AccessControl.tsx (2)

Line range hint 164-171: Add error handling to deleteSkilavottordAccessControl mutation

For consistency, add the same error handling pattern to the delete mutation as well.

 const [deleteSkilavottordAccessControl] = useMutation(
   DeleteSkilavottordAccessControlMutation,
   {
+    onError(_) {
+      console.error('Access Control deletion failed:', _)
+      if (_.networkError) {
+        // Handle network errors
+      } else if (_.graphQLErrors?.length) {
+        // Handle GraphQL errors
+      }
+      // Hide Runtime error message. The error message is already shown to the user in toast.
+    },
     refetchQueries: [
       {
         query: SkilavottordAccessControlsQuery,
       },
     ],
   },
 )

Line range hint 1-394: Overall implementation looks good with room for improvement

The component follows NextJS best practices and effectively uses TypeScript. The error handling improvements align with the PR objectives of preventing "Unhandled Runtime Error" messages.

Suggestions for further improvement:

  1. Consider implementing a centralized error handling utility for consistent error logging and handling across mutations
  2. Add error boundaries to catch any unhandled errors at the component level
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 70a3148 and ec5c9e6.

📒 Files selected for processing (3)
  • apps/skilavottord/web/screens/AccessControl/AccessControl.tsx (2 hunks)
  • apps/skilavottord/web/screens/RecyclingCompanies/RecyclingCompanyCreate/RecyclingCompanyCreate.tsx (1 hunks)
  • apps/skilavottord/ws/src/app/modules/accessControl/accessControl.resolver.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
apps/skilavottord/web/screens/AccessControl/AccessControl.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/skilavottord/web/screens/RecyclingCompanies/RecyclingCompanyCreate/RecyclingCompanyCreate.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/skilavottord/ws/src/app/modules/accessControl/accessControl.resolver.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (1)
apps/skilavottord/ws/src/app/modules/accessControl/accessControl.resolver.ts (1)

1-17: LGTM! Import changes align with error handling improvements.

The addition of ConflictException and the organization of imports follow NestJS best practices.

Copy link

codecov bot commented Oct 25, 2024

Codecov Report

Attention: Patch coverage is 0% with 8 lines in your changes missing coverage. Please review.

Project coverage is 36.76%. Comparing base (5d1f145) to head (282786e).
Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
...pp/modules/accessControl/accessControl.resolver.ts 0.00% 8 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16559      +/-   ##
==========================================
+ Coverage   36.67%   36.76%   +0.09%     
==========================================
  Files        6858     6853       -5     
  Lines      142787   142027     -760     
  Branches    40703    40479     -224     
==========================================
- Hits        52364    52221     -143     
+ Misses      90423    89806     -617     
Flag Coverage Δ
api 3.37% <ø> (ø)
application-system-api 41.32% <ø> (ø)
application-template-api-modules 27.79% <ø> (+0.01%) ⬆️
skilavottord-ws 24.14% <0.00%> (-0.05%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...ules/recyclingPartner/recyclingPartner.resolver.ts 0.00% <ø> (ø)
...pp/modules/accessControl/accessControl.resolver.ts 0.00% <0.00%> (ø)

... and 135 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update f0dd1e4...282786e. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 25, 2024

Datadog Report

All test runs 6f8c668 🔗

4 Total Test Services: 0 Failed, 4 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.05%), 5 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 3.2s 1 no change Link
application-system-api 0 0 0 120 2 3m 14.58s 1 no change Link
application-template-api-modules 0 0 0 123 0 2m 39.86s 1 no change Link
skilavottord-ws 0 0 0 1 0 17.2s 1 decreased (-0.05%) Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • skilavottord-ws - jest 25.24% (-0.05%) - Details

@birkirkristmunds birkirkristmunds changed the title chore(skilavottord): Have better error handling when creating access and companies fix(skilavottord): Have better error handling when creating access and companies Oct 25, 2024
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

🧹 Outside diff range and nitpick comments (1)
apps/skilavottord/ws/src/app/modules/recyclingPartner/recyclingPartner.resolver.ts (1)

Line range hint 1-93: Consider standardizing error messages across mutations.

While reviewing the error handling, I noticed that updateSkilavottordRecyclingPartner uses a different error message format compared to createSkilavottordRecyclingPartner. For consistency, consider including the companyId in the not found error message as well.

-      throw new NotFoundException("Recycling partner doesn't exists")
+      throw new NotFoundException(`Recycling partner with id ${input.companyId} doesn't exist`)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ec5c9e6 and 5a79133.

📒 Files selected for processing (2)
  • apps/skilavottord/ws/src/app/modules/accessControl/accessControl.resolver.ts (2 hunks)
  • apps/skilavottord/ws/src/app/modules/recyclingPartner/recyclingPartner.resolver.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/skilavottord/ws/src/app/modules/accessControl/accessControl.resolver.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/skilavottord/ws/src/app/modules/recyclingPartner/recyclingPartner.resolver.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (2)
apps/skilavottord/ws/src/app/modules/recyclingPartner/recyclingPartner.resolver.ts (2)

59-59: LGTM! Improved error message clarity.

The error message now includes the specific companyId, making it easier to identify which recycling partner caused the conflict.


Line range hint 1-93: Verify error handling in the frontend.

Since this PR aims to improve error handling and prevent "Unhandled Runtime Error" messages, ensure that the frontend properly handles these exceptions through toast notifications.

✅ Verification successful

Error handling is properly implemented in the frontend

The codebase has comprehensive error handling for GraphQL operations:

  • A global error link (errorLink.ts) handles all GraphQL errors and network errors, displaying them via toast notifications
  • The Apollo client is configured to show error messages through toast notifications for both network errors and GraphQL errors
  • Authentication/authorization errors are properly handled with appropriate redirects
  • The createSkilavottordRecyclingPartner mutation is used within a proper error handling context, where errors will be caught and displayed through the global error handler

The implementation ensures that the "Unhandled Runtime Error" messages will be properly caught and displayed to users through toast notifications.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for GraphQL mutation usage in frontend components
rg -t typescript -t tsx "createSkilavottordRecyclingPartner.*mutation" apps/skilavottord/web

# Search for error handling patterns
rg -t typescript -t tsx "onError.*toast" apps/skilavottord/web

Length of output: 229


Script:

#!/bin/bash
# Search for GraphQL mutation usage in frontend components without file type filters
rg "createSkilavottordRecyclingPartner.*mutation" apps/skilavottord/web

# Search for error handling patterns
rg "onError.*toast" apps/skilavottord/web

# Search for any toast-related error handling
rg "toast.*error" apps/skilavottord/web

# Look for mutation error handling patterns
rg "mutation.*catch" apps/skilavottord/web

# Search for GraphQL error handling patterns
rg "GraphQLError|ApolloError" apps/skilavottord/web

Length of output: 715


Script:

#!/bin/bash
# Check the error handling setup in Apollo client configuration
cat apps/skilavottord/web/graphql/errorLink.ts

# Look for the actual mutation implementation
rg -B2 -A2 "createSkilavottordRecyclingPartner" apps/skilavottord/web

Length of output: 3457

@birkirkristmunds birkirkristmunds changed the title fix(skilavottord): Have better error handling when creating access and companies fix(skilavottord): Improve error handling when creating access and companies Oct 25, 2024
Copy link
Member

@veronikasif veronikasif left a comment

Choose a reason for hiding this comment

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

lgtm 💯

@birkirkristmunds birkirkristmunds added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Oct 31, 2024
@kodiakhq kodiakhq bot merged commit 7adc95a into main Oct 31, 2024
40 checks passed
@kodiakhq kodiakhq bot deleted the chore/skilavottord-add-better-error-handling-when-creating-access-and-companies branch October 31, 2024 15:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deprecated:automerge (Disabled) Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants