Skip to content

fix: handle fb_custom_audience auth error - #4237

Merged
maheshkutty merged 6 commits into
developfrom
fix.fb_custom_audience_error_msg
Apr 8, 2025
Merged

maheshkutty merged 6 commits into
developfrom
fix.fb_custom_audience_error_msg

Conversation

@maheshkutty

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

We’re encountering the following error when the Facebook Custom Audience access token has expired:

{
  message: "The token has expired on Saturday, 23-Sep-23 23:29:14 PDT. The current time is Monday, 07-Apr-25 03:48:44 PDT.",
  type: "OAuthException",
  code: 190,
  fbtrace_id: "AxFa_0JxfQ4sctzqEQisyeJ"
}

This error wasn't being handled previously, which led to users seeing a generic base error message in the UI when looking for sample error responses.

We’ve updated the logic to explicitly handle this case by inspecting the error.message field in the payload.

What is the related Linear task?

Resolves INT-3393

Please explain the objectives of your changes below

Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here

Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?

N/A

Any new dependencies introduced with this change?

N/A

Any new generic utility introduced or modified. Please explain the changes.

N/A

Any technical or performance related pointers to consider with the change?

N/A

@coderabbitai review


Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced.

  • All related docs linked with the PR?

  • All changes manually tested?

  • Any documentation changes needed with this change?

  • Is the PR limited to 10 file changes?

  • Is the PR limited to one linear task?

  • Are relevant unit and component test-cases added in new readability format?

Reviewer checklist

  • Is the type of change in the PR title appropriate as per the changes?

  • Verified that there are no credentials or confidential data exposed with the changes.

@maheshkutty
maheshkutty requested review from a team and sivashanmukh as code owners April 7, 2025 12:40
@maheshkutty
maheshkutty requested review from a team, koladilip and utsabc April 7, 2025 12:40
@coderabbitai

coderabbitai Bot commented Apr 7, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error messaging now delivers clearer and more helpful notifications when issues occur, ensuring users receive more informative feedback.
  • Tests

    • Expanded automated test coverage across various error scenarios to confirm consistent and reliable error handling.

Walkthrough

This update refines the error handling logic within the errorResponseHandler function. The function now checks if an error message is falsy; if so, it retrieves the message from the error object or defaults to a predefined message. This adjustment applies to both ConfigurationAuthError and NetworkError cases. Additionally, a new test suite has been introduced to comprehensively cover various error scenarios, ensuring that appropriate error messages and statuses are returned in different conditions.

Changes

File(s) Change Summary
src/v0/util/facebookUtils/networkHandler.js Enhanced error handling by checking for falsy error messages and falling back to using details from the error object or a default message. Applied in both ConfigurationAuthError and NetworkError cases with clarifying comments.
src/v0/util/facebookUtils/networkHandler.test.ts Introduced a comprehensive suite of unit tests for the errorResponseHandler function, covering successful responses, auth errors (e.g., error code 190), network errors, dynamic messages, and generic error fallback scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant EH as ErrorResponseHandler

    C->>EH: Receives network response with error details
    Note over EH: Validate errorMessage is provided
    alt errorMessage exists
        EH->>C: Throw error using provided errorMessage
    else errorMessage is falsy
        EH->>EH: Retrieve error message from error object or use default
        alt error code is 190 (auth error)
            EH->>C: Throw ConfigurationAuthError with detailed message
        else
            EH->>C: Throw NetworkError with detailed message
        end
    end
Loading

Suggestions for Improvement

  • Refactoring: Consider extracting the fallback logic for error messages into a helper function to reduce repetition and improve clarity.
  • Type Validation: Enhance type validation for the error object to ensure that error properties are accessed safely.
  • Test Coverage: Incorporate additional edge cases in the tests, such as malformed error objects or unexpected error formats, to further reinforce robustness.
  • Logging: Optionally, add logging to capture error details before throwing exceptions, aiding in debugging and monitoring.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
src/v0/util/facebookUtils/networkHandler.test.js (1)

222-241: Duplicate test for rate limiting.

This test is similar to the previous rate limit test and validates the same behavior with a different error code. Consider consolidating these tests or using parameterized tests if your testing framework supports it.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ba03a0 and 7afa34e.

⛔ Files ignored due to path filters (2)
  • test/integrations/destinations/fb_custom_audience/dataDelivery/data.ts is excluded by !**/test/**
  • test/integrations/destinations/fb_custom_audience/network.ts is excluded by !**/test/**
📒 Files selected for processing (2)
  • src/v0/util/facebookUtils/networkHandler.js (1 hunks)
  • src/v0/util/facebookUtils/networkHandler.test.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.js`: Focus on ESLint errors (max 3) and warnings (max 5).

**/*.js: Focus on ESLint errors (max 3) and warnings (max 5).

  • src/v0/util/facebookUtils/networkHandler.js
  • src/v0/util/facebookUtils/networkHandler.test.js
🧬 Code Definitions (1)
src/v0/util/facebookUtils/networkHandler.js (1)
src/v0/util/index.js (1)
  • isDefinedAndNotNull (49-49)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: ingestion-service-test
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (14)
src/v0/util/facebookUtils/networkHandler.js (3)

272-275: Good addition of clarifying comments.

The comment clearly explains the intent behind the subsequent code changes, helping other developers understand why this check is needed to avoid using a generic base error message.


279-282: Improved error message handling.

This change effectively handles the Facebook OAuth expiration errors by providing a proper fallback mechanism when the errorMessage is falsy. It will now use the error.message field which contains important details about token expiration (as seen in the test).


284-286: Similar improvement for NetworkError handling.

The same fallback pattern is consistently applied here, which is good for code uniformity. This ensures meaningful error messages are provided regardless of the error type.

src/v0/util/facebookUtils/networkHandler.test.js (11)

1-14: Good test setup for successful responses.

The test file starts with the appropriate imports and a basic test to verify no errors are thrown when the response is successful, establishing a baseline for further tests.


16-36: Appropriate test for basic AUTH error handling.

This test verifies that ConfigurationAuthError is thrown with the correct message and status code when an OAuth error occurs with error_user_msg present.


38-58: Good test for NetworkError with appropriate error details.

The test validates that NetworkError is thrown with the correct message from error_user_title when specific error codes are encountered.


60-84: Validates fallback for unknown error codes.

This test ensures the system can handle unexpected error codes by returning a stringified version of the error object.


86-105: Effectively tests rate limit error scenarios.

The test confirms that rate limit errors are properly identified and reported with the appropriate status code (429).


107-127: Comprehensive test for OAuth token errors.

This test validates handling of invalid OAuth token errors with appropriate error codes and messages.


129-153: Critical test for the PR objective - expired token handling.

This test directly validates the fix implemented in this PR, ensuring that when a token has expired, the system extracts the detailed message from the error.message field. The test data closely resembles a real-world Facebook API response with expiration timestamp information.


155-176: Verifies default message fallback.

This test ensures that when both errorMessage and error.message are empty/falsy, the system falls back to the default "Unknown auth error" message, covering an important edge case.


178-197: Validates handling of unrecognized error subcodes.

This test ensures proper fallback to the default message when encountering an unknown error subcode, which is important for robustness.


199-220: Tests custom audience specific error handling.

This test validates the specific error message for custom audience unavailability, which is relevant to the PR's focus on Facebook Custom Audience functionality.


243-262: Validates unhandled error scenarios.

This final test ensures the system can gracefully handle completely unexpected error codes, which is important for production stability.

@maheshkutty maheshkutty changed the title fix: handle fb_custom_audience oauth error fix: handle fb_custom_audience auth error Apr 7, 2025
@codecov

codecov Bot commented Apr 7, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.06%. Comparing base (322ddbc) to head (e912e80).
Report is 13 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4237      +/-   ##
===========================================
+ Coverage    91.05%   91.06%   +0.01%     
===========================================
  Files          627      630       +3     
  Lines        33049    33049              
  Branches      7818     7826       +8     
===========================================
+ Hits         30092    30096       +4     
- Misses        2710     2736      +26     
+ Partials       247      217      -30     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (4)
src/v0/util/facebookUtils/networkHandler.test.ts (4)

67-92: Consider more descriptive test naming for default error scenario.

While the test itself is well-structured, the description could be more specific about what "details are not found" means in this context.

- it('should throw a NetworkError with default message when error details are not found', () => {
+ it('should throw a NetworkError with stringified error object when error_user_msg is missing', () => {

190-210: Consider clarifying test description for this case.

The test name suggests stringifying the error object, but the actual assertion tests for a default message.

- it('should throw a NetworkError with error object as stringified', () => {
+ it('should throw a NetworkError with default message for unknown error code', () => {

258-279: Unnecessary conditional check in the catch block.

The conditional check on line 272 is redundant since expect.assertions(3) already ensures that the catch block will be executed with a valid error.

    try {
      errorResponseHandler(destResponse);
    } catch (e) {
-      if (e) {
        expect(e).toBeInstanceOf(NetworkError);
        const error = e as CommonErrorType;
        expect(error.message).toBe('Unhandled error.');
        expect(error.status).toBe(500);
-      }
    }

1-280: Overall excellent test coverage for the errorResponseHandler function.

The test suite provides comprehensive coverage of various error scenarios, with particular attention to Facebook OAuth errors that are the focus of this PR. The tests are well-structured, consistent in format, and verify both error types and messages appropriately.

Consider adding some comments to explain what the various Facebook error codes represent (e.g., 190 for auth errors, 4 and 17 for rate limits, etc.) to improve code maintainability for future developers.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7afa34e and d1ab25b.

📒 Files selected for processing (1)
  • src/v0/util/facebookUtils/networkHandler.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: ingestion-service-test
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (10)
src/v0/util/facebookUtils/networkHandler.test.ts (10)

1-9: Well-structured imports and type definition.

Clean imports and a clear TypeScript type definition for common errors. This sets the stage for the test suite to follow.


10-19: Good initial test case verifying the happy path.

The first test appropriately checks that no error is thrown when there's no error in the response, establishing the baseline behavior of the function.


21-42: Well-written authentication error test.

This test correctly verifies that a ConfigurationAuthError is thrown for authentication errors with appropriate message and status. The use of expect.assertions ensures that the catch block is executed.


44-65: Proper testing of network error with detailed error information.

This test case effectively validates the NetworkError behavior when specific error details are available in the response.


94-114: Comprehensive test for rate limit error scenario.

Good test case covering rate limiting scenarios with appropriate status code (429).


116-137: Complete test for auth error with different subcode.

This test complements the earlier auth error test by covering a different error_subcode value.


139-164: Excellent test covering the core PR objective.

This test case directly addresses the PR objective of handling expired Facebook access tokens. The detailed error message with token expiration date is properly validated.


166-188: Good edge case handling for empty auth error messages.

This test ensures appropriate fallback behavior when an auth error occurs but no specific message is provided.


212-234: Good test for custom audience specific error.

This test validates the specific error handling for Custom Audience unavailability, which aligns well with the PR's focus on Facebook Custom Audience auth errors.


236-256: Complete rate limit test with alternative error code.

This test complements the earlier rate limit test by covering error code 17, ensuring comprehensive coverage of rate limiting scenarios.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

vinayteki95
vinayteki95 previously approved these changes Apr 7, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
src/v0/util/facebookUtils/networkHandler.test.ts (1)

1-1: Table test format successfully implemented.

This implementation addresses the previous review comment that requested "Use LLM and convert this into table tests format." The current structure provides a clean, maintainable way to test multiple scenarios.

🧹 Nitpick comments (1)
src/v0/util/facebookUtils/networkHandler.test.ts (1)

199-213: Well-implemented test execution logic.

The test.each implementation effectively validates all three critical components of each error:

  1. The error class type
  2. The error message content
  3. The HTTP status code

Consider adding a type guard before the type assertion on line 207 for added safety:

- const error = e as CommonErrorType;
+ const error = e instanceof Error ? e as CommonErrorType : e;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 32195f2 and f95798b.

📒 Files selected for processing (1)
  • src/v0/util/facebookUtils/networkHandler.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Code Coverage
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: ingestion-service-test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
src/v0/util/facebookUtils/networkHandler.test.ts (3)

1-7: Imports and type definition look good.

Clean imports of the necessary error classes and the function under test. The CommonErrorType is well-defined and appropriately used in the test implementation.


9-13: Good baseline test for the success case.

Starting with a test for the happy path ensures basic functionality is covered before diving into error scenarios.


15-197: Comprehensive test coverage for error scenarios.

The table-driven approach provides excellent coverage of various error conditions including:

  • Authentication errors with different error codes
  • Network errors with different messages
  • Rate limiting scenarios
  • The custom audience-specific errors addressed in this PR

Your test for expired tokens (lines 100-118) directly addresses the PR objective of handling Facebook Custom Audience access token expiration.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@maheshkutty
maheshkutty requested a review from vinayteki95 April 8, 2025 04:54
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

sonarqubecloud Bot commented Apr 8, 2025

Copy link
Copy Markdown

@maheshkutty
maheshkutty merged commit ab427cd into develop Apr 8, 2025
@maheshkutty
maheshkutty deleted the fix.fb_custom_audience_error_msg branch April 8, 2025 06:38
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.

4 participants