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): Fix error message being shown if vehicle is not found for registration #16852

Merged

Conversation

birkirkristmunds
Copy link
Member

@birkirkristmunds birkirkristmunds commented Nov 13, 2024

TS-933

What

Don't show error when canceling de-registration
Fixed typo

Why

Error is being shown when canceling shown if vehicle is not found for de-registration.

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 vehicle deregistration queries to maintain a seamless user experience.
  • Bug Fixes

    • Improved error reporting by using specific exceptions for vehicle deregistration requests.
  • Refactor

    • Reordered import statements in various components for better clarity without affecting functionality.
  • Chores

    • Reformatted return statements in utility functions for improved readability.

@birkirkristmunds birkirkristmunds requested a review from a team as a code owner November 13, 2024 14:36
Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

Walkthrough

The pull request introduces several modifications primarily focused on enhancing error handling across various components related to vehicle deregistration. Key changes include the addition of specific error handling logic in the GraphQL error link and the Confirm component, as well as improved exception handling in the RecyclingRequestService. Additionally, there are minor adjustments to import statements for clarity in the Overview component and a formatting update in the roleUtils file.

Changes

File Path Change Summary
apps/skilavottord/web/graphql/errorLink.ts Removed import of signOut; added condition for FORBIDDEN and NOT_FOUND errors in onError function.
apps/skilavottord/web/screens/DeregisterVehicle/Confirm/Confirm.tsx Added onError callback to useQuery for SkilavottordVehicleReadyToDeregisteredQuery; no UI updates on error.
apps/skilavottord/web/screens/DeregisterVehicle/Overview/Overview.tsx Reordered import statements for clarity; no functional changes.
apps/skilavottord/web/utils/roleUtils.ts Reformatted return statement in getRoleTranslation function for readability; no functional changes.
apps/skilavottord/ws/src/app/modules/recyclingRequest/recyclingRequest.service.ts Updated getVehicleInfoToDeregistered method to throw NotFoundException with logging; refined error handling.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • veronikasif
  • thordurhhh

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

🧹 Outside diff range and nitpick comments (6)
apps/skilavottord/web/graphql/errorLink.ts (2)

25-28: Improve type safety for error extensions

The error handling logic is correct and aligns with the PR objective. However, the type casting can be improved.

Consider creating a type for the error response structure:

type GraphQLErrorExtensions = {
  code?: string;
  response?: {
    error?: string;
  };
};

// Then use it instead of 'any':
(graphQLErrors[0]?.extensions as GraphQLErrorExtensions)?.response?.error === 'NOT_FOUND'

25-28: Consider adding user feedback for NOT_FOUND cases

While silently handling the error prevents unwanted error messages, users might benefit from knowing that the vehicle wasn't found.

Consider showing an informative toast message:

    } else if (
      errorCodes.includes('FORBIDDEN') ||
      (graphQLErrors[0]?.extensions as any)?.response?.error === 'NOT_FOUND'
    ) {
+     if ((graphQLErrors[0]?.extensions as any)?.response?.error === 'NOT_FOUND') {
+       toast.info('Vehicle not found in the system')
+     }
      return
    }
apps/skilavottord/web/screens/DeregisterVehicle/Confirm/Confirm.tsx (3)

136-138: Consider improving error handling clarity

While delegating error handling to ErrorLink is valid, consider these improvements:

  1. Remove the empty callback since it's not performing any action
  2. If kept, add type information for better type safety: onError: (err: ApolloError) => void
  3. Enhance the comment to explain why errors are handled in ErrorLink
-      onError: (_err) => {
-        // Do nothing error handled in ErrorLink
-      },
+      // Errors are handled globally in ErrorLink to prevent UI error messages
+      // for expected cases like vehicle not found

Line range hint 1-324: Consider architectural improvements for error handling consistency

The component's error handling could be more consistent and type-safe:

  1. Standardize error handling approach across queries and mutations
  2. Use TypeScript discriminated unions for better error type safety
  3. Consolidate loading states for improved user experience

Consider creating a custom hook to encapsulate the error handling logic:

type QueryResult<T> = {
  data?: T;
  loading: boolean;
  error?: ApolloError;
};

function useVehicleQuery(id: string): QueryResult<Vehicle> {
  const vehicleQuery = useQuery(SkilavottordVehicleReadyToDeregisteredQuery, {
    variables: { permno: id },
    // Errors handled globally in ErrorLink
  });

  const trafficQuery = useQuery(SkilavottordTrafficQuery, {
    variables: { permno: id },
    skip: !vehicleQuery.data,
  });

  return {
    data: vehicleQuery.data?.skilavottordVehicleReadyToDeregistered,
    loading: vehicleQuery.loading || trafficQuery.loading,
    error: vehicleQuery.error || trafficQuery.error,
  };
}

Line range hint 1-324: Enhance NextJS implementation for better performance and UX

Consider these NextJS-specific improvements:

  1. Implement getStaticProps or getServerSideProps for initial data fetching
  2. Add proper loading skeleton UI instead of just loading dots
  3. Implement error boundaries for better error handling

Example implementation:

// pages/deregister-vehicle/confirm/[id].tsx
export const getServerSideProps: GetServerSideProps = async (context) => {
  const { id } = context.params;
  const apolloClient = initializeApollo();

  try {
    const { data } = await apolloClient.query({
      query: SkilavottordVehicleReadyToDeregisteredQuery,
      variables: { permno: id },
    });

    return {
      props: {
        initialApolloState: apolloClient.cache.extract(),
        vehicle: data.skilavottordVehicleReadyToDeregistered,
      },
    };
  } catch (error) {
    return {
      props: {
        initialApolloState: apolloClient.cache.extract(),
        error: error.message,
      },
    };
  }
};
apps/skilavottord/ws/src/app/modules/recyclingRequest/recyclingRequest.service.ts (1)

167-172: Improved error handling, but could be more DRY

The changes correctly implement NestJS exception handling and improve error traceability. However, there are a few potential improvements:

  1. The warning log and error message are duplicative
  2. The error code could be extracted as a constant for reusability

Consider this refactoring:

+ const NOT_FOUND_ERROR = 'NOT_FOUND';
+ const getNotFoundMessage = (loggedPermno: string, partnerId: string) =>
+   `Could not find any requestType for vehicle's number: ${loggedPermno} in database from partner ${partnerId}`;

- this.logger.warn(
-   `car-recycling: Could not find any requestType for vehicle's number: ${loggedPermno} in database from partner ${user.partnerId}`,
- )
- throw new NotFoundException(
-   `Could not find any requestType for vehicle's number: ${loggedPermno} in database from partner ${user.partnerId}`,
-   'NOT_FOUND',
- )
+ const errorMessage = getNotFoundMessage(loggedPermno, user.partnerId);
+ this.logger.warn(`car-recycling: ${errorMessage}`);
+ throw new NotFoundException(errorMessage, NOT_FOUND_ERROR);

Also applies to: 185-188

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2401e53 and bea4271.

📒 Files selected for processing (5)
  • apps/skilavottord/web/graphql/errorLink.ts (2 hunks)
  • apps/skilavottord/web/screens/DeregisterVehicle/Confirm/Confirm.tsx (1 hunks)
  • apps/skilavottord/web/screens/DeregisterVehicle/Overview/Overview.tsx (1 hunks)
  • apps/skilavottord/web/utils/roleUtils.ts (1 hunks)
  • apps/skilavottord/ws/src/app/modules/recyclingRequest/recyclingRequest.service.ts (3 hunks)
✅ Files skipped from review due to trivial changes (2)
  • apps/skilavottord/web/screens/DeregisterVehicle/Overview/Overview.tsx
  • apps/skilavottord/web/utils/roleUtils.ts
🧰 Additional context used
📓 Path-based instructions (3)
apps/skilavottord/web/graphql/errorLink.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."
apps/skilavottord/web/screens/DeregisterVehicle/Confirm/Confirm.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/recyclingRequest/recyclingRequest.service.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/recyclingRequest/recyclingRequest.service.ts (1)

1-6: LGTM! Clean import organization

The addition of NotFoundException follows NestJS best practices for HTTP exception handling.

Copy link

codecov bot commented Nov 13, 2024

Codecov Report

Attention: Patch coverage is 20.00000% with 4 lines in your changes missing coverage. Please review.

Project coverage is 35.86%. Comparing base (55aae3d) to head (630b0da).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...dules/recyclingRequest/recyclingRequest.service.ts 20.00% 4 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16852      +/-   ##
==========================================
+ Coverage   35.74%   35.86%   +0.12%     
==========================================
  Files        6937     6898      -39     
  Lines      148174   146648    -1526     
  Branches    42253    41785     -468     
==========================================
- Hits        52969    52601     -368     
+ Misses      95205    94047    -1158     
Flag Coverage Δ
api 3.33% <ø> (ø)
application-system-api 38.73% <ø> (-0.01%) ⬇️
application-template-api-modules 27.82% <ø> (ø)
skilavottord-ws 24.26% <20.00%> (-0.05%) ⬇️

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

Files with missing lines Coverage Δ
...dules/recyclingRequest/recyclingRequest.service.ts 8.96% <20.00%> (-0.13%) ⬇️

... and 661 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 55aae3d...630b0da. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 13, 2024

Datadog Report

All test runs 8b187f6 🔗

4 Total Test Services: 0 Failed, 4 Passed
🔻 Test Sessions change in coverage: 2 decreased, 4 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 2.74s 1 no change Link
application-system-api 0 0 0 46 0 2m 11.54s 1 no change Link
application-template-api-modules 0 0 0 118 0 2m 7.01s 1 decreased (-0.01%) Link
skilavottord-ws 0 0 0 1 0 13.79s 1 decreased (-0.05%) Link

🔻 Code Coverage Decreases vs Default Branch (2)

  • skilavottord-ws - jest 25.39% (-0.05%) - Details
  • application-template-api-modules - jest 30.2% (-0.01%) - Details

@birkirkristmunds birkirkristmunds added the automerge Merge this PR as soon as all checks pass label Nov 13, 2024
@coderabbitai coderabbitai bot mentioned this pull request Nov 19, 2024
6 tasks
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 👍

@kodiakhq kodiakhq bot merged commit 28c639f into main Dec 13, 2024
44 checks passed
@kodiakhq kodiakhq bot deleted the fix/skilavottord-error-shown-after-cancel-deregistration branch December 13, 2024 17:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants