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

feat: added skip for handled response exceptions #2862

Merged
merged 3 commits into from
Nov 25, 2024

Conversation

chesterkmr
Copy link
Collaborator

@chesterkmr chesterkmr commented Nov 21, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced user management functions for Sentry and PostHog to enhance user tracking and monitoring.
    • Added fetchEndUser and createEndUserRequest functions for improved user data retrieval and creation.
    • Implemented error handling improvements to selectively ignore certain exceptions.
  • Bug Fixes

    • Enhanced error handling logic in the request function, improving context for logged errors.
  • Refactor

    • Updated useEndUserQuery hook to manage user information in monitoring systems more effectively.

Copy link

changeset-bot bot commented Nov 21, 2024

⚠️ No Changeset found

Latest commit: 820fd99

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

Copy link
Contributor

coderabbitai bot commented Nov 21, 2024

Walkthrough

This pull request introduces several changes across multiple files in the kyb-app project. Key modifications include the addition of error handling functions, the restructuring of user data interfaces, and enhancements to monitoring user interactions with Sentry and PostHog. Specifically, new functions for user management and improved error handling logic are implemented, allowing for selective error ignoring and better context in error reporting. The overall structure and functionality of existing methods remain largely intact, with some updates to variable names for clarity.

Changes

File Path Change Summary
apps/kyb-app/src/common/providers/DependenciesProvider/helpers.ts - Added isShouldIgnoreErrors function.
- Updated logic to call isExceptionWillBeHandled.
apps/kyb-app/src/common/utils/helpers.ts - Introduced isExceptionWillBeHandled function to evaluate error handling.
apps/kyb-app/src/common/utils/request.ts - Modified error handling in request function.
- Added import for isExceptionWillBeHandled.
- Introduced logic to determine if errors should be ignored.
apps/kyb-app/src/domains/collection-flow/collection-flow.api.ts - Added EndUser interface and fetchEndUser function.
- Introduced CreateEndUserDto interface and createEndUserRequest function.
apps/kyb-app/src/hooks/useEndUserQuery/useEndUserQuery.ts - Renamed data to endUser.
- Added imports for user management functions and updated logic to manage user info in Sentry and PostHog.
apps/kyb-app/src/initialize-monitoring/initialize-monitoring.ts - Added functions: updateSentryUser, updatePostHogUser, clearSentryUser, and clearPostHogUser for user management in monitoring systems.

Possibly related PRs

  • Posthog leftovers #2612: Introduces posthog-js, which is relevant to the error handling changes in the main PR that may involve analytics tracking.

Suggested reviewers

  • alonp99
  • Omri-Levy

🐇 In the code where errors may creep,
A new function wakes from sleep.
With Sentry and PostHog in view,
We track the users, old and new.
So hop along, let changes flow,
In our app, watch the magic grow! 🌟


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.

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.

@chesterkmr chesterkmr changed the title feat: added skip for handled response exceptions & updated sentry met… feat: added skip for handled response exceptions Nov 21, 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: 9

🧹 Outside diff range and nitpick comments (7)
apps/kyb-app/src/hooks/useEndUserQuery/useEndUserQuery.ts (2)

24-46: Add null checks for user properties

While the monitoring integration is well-structured, it's important to validate user properties before usage.

   useEffect(() => {
-    if (endUser) {
+    if (endUser?.id && endUser?.email && endUser?.firstName && endUser?.lastName) {
       updateSentryUser({
         id: endUser.id,
         email: endUser.email,
         fullName: `${endUser.firstName} ${endUser.lastName}`,
       });

Line range hint 48-53: Consider using type guard for error handling

The current error casting could be improved using a type guard for better type safety.

-    error: error ? (error as HTTPError) : null,
+    error: error instanceof HTTPError ? error : null,
apps/kyb-app/src/common/utils/request.ts (1)

29-37: Optimize response handling and improve error clarity

The code makes multiple calls to response.clone() and might silently ignore parsing errors.

Consider consolidating the response handling:

-responseBody = await error.response.clone().text();
-const responseJson = await error.response.clone().json();
+const clonedResponse = error.response.clone();
+responseBody = await clonedResponse.text();
+let responseJson;
+try {
+  responseJson = JSON.parse(responseBody);
+} catch (parseError) {
+  console.warn('Failed to parse error response as JSON:', responseBody);
+  throw error;
+}
apps/kyb-app/src/initialize-monitoring/initialize-monitoring.ts (1)

53-63: Add input validation and document the fullName mapping.

While the function works correctly, consider these improvements:

  1. Add input validation to ensure data quality before sending to Sentry
  2. Document why fullName is mapped to username in Sentry context
 export const updateSentryUser = (userMetadata: {
   id?: string;
   email?: string;
   fullName?: string;
 }) => {
+  // Validate inputs
+  if (userMetadata.email && !userMetadata.email.includes('@')) {
+    console.warn('Invalid email format provided to updateSentryUser');
+    return;
+  }
+
+  // Map fullName to username for Sentry's conventional user context structure
   Sentry.setUser({
     id: userMetadata.id,
     email: userMetadata.email,
     username: userMetadata.fullName,
   });
 };
apps/kyb-app/src/domains/collection-flow/collection-flow.api.ts (3)

Line range hint 13-26: Consider enhancing error logging with additional context

While the PostHog error handling is properly isolated, consider adding more context to the error logging to align with the PR's objective of improving monitoring metadata.

     } catch (error) {
-      console.error('Error identifying user in PostHog:', error);
+      console.error('Error identifying user in PostHog:', {
+        error,
+        userId: user.id,
+        context: 'fetchUser',
+      });
     }

Line range hint 95-111: Add consistent error handling to new user management functions

The new user-related functions lack error handling, which is inconsistent with the error handling pattern used in fetchFlowContext. Consider adding proper error handling to align with the PR's objective of managing response exceptions.

 export const fetchEndUser = async (): Promise<EndUser> => {
-  const result = await request.get('collection-flow/user');
-  return result.json<EndUser>();
+  try {
+    const result = await request.get('collection-flow/user');
+    const user = await result.json<EndUser>();
+    
+    if (!user || typeof user !== 'object') {
+      throw new Error('Invalid user data received');
+    }
+    
+    return user;
+  } catch (error) {
+    console.error('Error fetching end user:', error);
+    throw error;
+  }
 };

 export interface CreateEndUserDto {
   email: string;
   firstName: string;
   lastName: string;
 }

 export const createEndUserRequest = async ({ email, firstName, lastName }: CreateEndUserDto) => {
-  await request.post('collection-flow/no-user', { json: { email, firstName, lastName } });
+  try {
+    await request.post('collection-flow/no-user', { json: { email, firstName, lastName } });
+  } catch (error) {
+    console.error('Error creating end user:', {
+      error,
+      context: 'createEndUserRequest',
+      email,
+    });
+    throw error;
+  }
 };

Line range hint 41-93: Standardize error handling across all API functions

The file shows inconsistent error handling patterns. While fetchFlowContext implements proper error handling with response validation, other functions like fetchUISchema, updateLanguage, and fetchCustomer lack similar protections.

Consider implementing a consistent error handling strategy across all API functions:

  1. Validate response data
  2. Add proper error context
  3. Handle specific error cases that can be safely skipped (as per PR objectives)

Example pattern to follow:

const apiHandler = async <T>(
  operation: () => Promise<T>,
  context: string,
  validate?: (data: T) => boolean
): Promise<T> => {
  try {
    const result = await operation();
    if (validate && !validate(result)) {
      throw new Error(`Invalid ${context} data`);
    }
    return result;
  } catch (error) {
    if (shouldSkipError(error)) {
      console.warn(`Skipping handled error in ${context}:`, error);
      return null as T;
    }
    console.error(`Error in ${context}:`, error);
    throw error;
  }
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c25d4a3 and 18e0fc6.

📒 Files selected for processing (6)
  • apps/kyb-app/src/common/providers/DependenciesProvider/helpers.ts (2 hunks)
  • apps/kyb-app/src/common/utils/helpers.ts (1 hunks)
  • apps/kyb-app/src/common/utils/request.ts (2 hunks)
  • apps/kyb-app/src/domains/collection-flow/collection-flow.api.ts (1 hunks)
  • apps/kyb-app/src/hooks/useEndUserQuery/useEndUserQuery.ts (1 hunks)
  • apps/kyb-app/src/initialize-monitoring/initialize-monitoring.ts (1 hunks)
🔇 Additional comments (8)
apps/kyb-app/src/common/utils/helpers.ts (1)

1-1: Verify error type handling across the codebase

The HTTPError import from 'ky' is used to type the error parameter. Let's verify this is consistent with error handling elsewhere.

✅ Verification successful

Based on the gathered information, I can now provide a final response:

HTTPError handling is consistent across the codebase

The HTTPError import from 'ky' is used consistently throughout the codebase for error handling, particularly in:

  • Common utility functions like isExceptionWillBeHandled
  • API request wrapper in request.ts
  • Various hooks (useEndUserQuery, useFlowContextQuery, etc.)
  • File upload and document handling components

The error handling follows a centralized pattern where:

  1. The base request utility (request.ts) handles common HTTP errors
  2. Specific error cases are handled through the isExceptionWillBeHandled helper
  3. Components and hooks properly type their error handling with HTTPError
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how HTTPError is used across the codebase for consistency

# Check for HTTPError imports
echo "Checking HTTPError imports:"
rg --type ts "import.*HTTPError.*from 'ky'" -A 2

# Check for error handling patterns
echo "\nChecking error handling patterns:"
ast-grep --pattern 'catch ($error) { $$$}' --lang ts

Length of output: 4833


Script:

#!/bin/bash
# Let's check the error handling patterns with a more specific search

# Check how HTTPError is used in catch blocks
echo "Checking HTTPError usage in catch blocks:"
rg --type ts "catch.*\(.*HTTPError" -A 3

# Check the implementation of error handling function
echo "\nChecking error handling implementation:"
rg --type ts "isExceptionWillBeHandled" -A 3

Length of output: 1813


Script:

#!/bin/bash
# Let's check for other error handling patterns in the codebase

# Check for error handling in try-catch blocks
echo "Checking try-catch blocks with HTTPError:"
rg --type ts "try\s*{[^}]*}\s*catch.*HTTPError" -A 5

# Check for other HTTP error types being used
echo "\nChecking for other HTTP error types:"
rg --type ts "import.*Error.*from" -A 2

# Check where the request utility is used
echo "\nChecking request utility usage:"
rg --type ts "import.*request.*from.*utils/request" -A 2

Length of output: 63169

apps/kyb-app/src/hooks/useEndUserQuery/useEndUserQuery.ts (2)

2-7: LGTM: Clean import structure

The new monitoring-related imports are well-organized and follow proper naming conventions.


13-15: LGTM: Improved variable naming

Renaming data to endUser enhances code readability by making the variable's purpose more explicit.

apps/kyb-app/src/common/utils/request.ts (1)

4-4: Verify the implementation of isExceptionWillBeHandled helper

Let's ensure the helper function exists and properly implements the error handling logic.

✅ Verification successful

Helper function implementation found and verified

The isExceptionWillBeHandled helper function is implemented in apps/kyb-app/src/common/utils/helpers.ts and specifically handles the case when no EndUser is set for a token:

export const isExceptionWillBeHandled = (error: HTTPError) => {
  return error.message === 'No EndUser is set for this token';
};
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of isExceptionWillBeHandled helper

# Search for the helper function implementation
ast-grep --pattern 'export const isExceptionWillBeHandled = $_'

# Search for any tests covering this helper
rg -l "isExceptionWillBeHandled.*test" -g "*.{ts,tsx,js,jsx}"

Length of output: 16465

apps/kyb-app/src/initialize-monitoring/initialize-monitoring.ts (3)

75-77: LGTM!

The function correctly implements Sentry's recommended way to clear user context.


79-81: LGTM!

The function correctly implements PostHog's recommended way to reset user identification.


52-81: Verify the completeness of the PR changes.

While these changes enhance user metadata management for monitoring tools, I don't see any implementation related to "skip for handled response exceptions" as mentioned in the PR objectives.

apps/kyb-app/src/domains/collection-flow/collection-flow.api.ts (1)

Line range hint 1-111: Verify Sentry integration and exception handling strategy

To ensure alignment with PR objectives, please clarify:

  1. Which specific response exceptions should be skipped
  2. How Sentry metadata is being updated for error tracking

@alonp99 alonp99 merged commit d5bc3ba into dev Nov 25, 2024
10 checks passed
@alonp99 alonp99 deleted the illiar/feat/sentry-exceptions branch November 25, 2024 14:50
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.

3 participants