-
Notifications
You must be signed in to change notification settings - Fork 199
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
Conversation
|
WalkthroughThis pull request introduces several changes across multiple files in the Changes
Possibly related PRs
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 propertiesWhile 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 handlingThe 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 clarityThe 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:
- Add input validation to ensure data quality before sending to Sentry
- Document why
fullName
is mapped tousername
in Sentry contextexport 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 contextWhile 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 functionsThe 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 functionsThe file shows inconsistent error handling patterns. While
fetchFlowContext
implements proper error handling with response validation, other functions likefetchUISchema
,updateLanguage
, andfetchCustomer
lack similar protections.Consider implementing a consistent error handling strategy across all API functions:
- Validate response data
- Add proper error context
- 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
📒 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:
- The base request utility (
request.ts
) handles common HTTP errors - Specific error cases are handled through the
isExceptionWillBeHandled
helper - 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:
- Which specific response exceptions should be skipped
- How Sentry metadata is being updated for error tracking
Summary by CodeRabbit
Release Notes
New Features
fetchEndUser
andcreateEndUserRequest
functions for improved user data retrieval and creation.Bug Fixes
Refactor
useEndUserQuery
hook to manage user information in monitoring systems more effectively.