Skip to content

fix: avoid empty catch blocks in analytics#99

Merged
kpj2006 merged 3 commits intoAOSSIE-Org:mainfrom
krishnan05:fix/analytics-lint-empty-catch
Mar 17, 2026
Merged

fix: avoid empty catch blocks in analytics#99
kpj2006 merged 3 commits intoAOSSIE-Org:mainfrom
krishnan05:fix/analytics-lint-empty-catch

Conversation

@krishnan05
Copy link
Contributor

@krishnan05 krishnan05 commented Mar 13, 2026

Addressed Issues:

Fixes #98

Screenshots/Recordings:

N/A — no UI changes.

Additional Notes:

Lint was failing on main due to empty catch blocks in the analytics section of src/social-share-button.js. This change adds brief comments inside those blocks to satisfy eslint no-empty without changing behavior.

Tests: npm run lint

AI Usage Disclosure:

We encourage contributors to use AI tools responsibly when creating Pull Requests. While AI can be a valuable aid, it is essential to ensure that your contributions meet the task requirements, build successfully, include relevant tests, and pass all linters. Submissions that do not meet these standards may be closed without warning to maintain the quality and integrity of the project. Please take the time to understand the changes you are proposing and their impact. AI slop is strongly discouraged and may lead to banning and blocking. Do not spam our repos with AI slop.

Check one of the checkboxes below:

  • This PR does not contain AI-generated code at all.
  • This PR contains AI-generated code. I have read the AI Usage Policy and this PR complies with this policy. I have tested the code locally and I am responsible for it.

I have used the following AI models and tools: OpenAI Codex (ChatGPT)

Checklist

  • My PR addresses a single issue, fixes a single bug or makes a single improvement.
  • My code follows the project's code style and conventions
  • If applicable, I have made corresponding changes or additions to the documentation
  • If applicable, I have made corresponding changes or additions to tests
  • My changes generate no new warnings or errors
  • I have joined the Discord server and I will share a link to this PR with the project maintainers there
  • I have read the Contribution Guidelines
  • Once I submit my PR, CodeRabbit AI will automatically review it and I will address CodeRabbit's comments.
  • I have filled this PR template completely and carefully, and I understand that my PR may be closed without review otherwise.

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling for analytics delivery and callbacks to avoid silent failures and reduce disruptions.
    • Safer handling of analytics plugins to prevent plugin errors from impacting the UI.
  • Technical Improvements

    • Better modal/open-state tracking for more reliable open/close behavior and consistent UX.
    • Added debug-only logging to surface analytics issues during diagnosis.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 13, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 516b2a05-14ce-470b-8640-133c64f3f004

📥 Commits

Reviewing files that changed from the base of the PR and between 2340ded and 53bf2c1.

📒 Files selected for processing (1)
  • src/social-share-button.js

Walkthrough

Added a debug-only warning helper and replaced empty catch blocks in analytics emission with guarded try/catch logging; added Array.isArray guard when iterating analytics plugins; introduced two static properties on SocialShareButton for shared modal state.

Changes

Cohort / File(s) Summary
Analytics handling & static state
src/social-share-button.js
Added _debugWarn(message, err); replaced empty catch blocks in _emit (DOM event dispatch, onAnalytics callback) with _debugWarn; guarded analyticsPlugins with Array.isArray(...), wrapped plugin.track(payload) calls in try/catch using _debugWarn; added static properties SocialShareButton.openModalCount = 0 and SocialShareButton.originalBodyOverflow = null.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Suggested labels

Typescript Lang, Linter, Documentation

Suggested reviewers

  • kpj2006

Poem

🐰 I nudged the empty catches away,
I whisper warnings when debug says play,
Two counters watch the modal swing,
I log small clues when troubles sting,
🥕 Hopping on, I celebrate the change.

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR introduces static properties (openModalCount, originalBodyOverflow) that appear unrelated to the stated goal of fixing empty catch blocks in analytics. Remove the unrelated static properties (openModalCount, originalBodyOverflow) or clarify their necessity in the PR description and ensure they are linked to addressing the eslint no-empty errors.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: avoid empty catch blocks in analytics' accurately describes the main change: addressing empty catch blocks in the analytics code to satisfy eslint rules.
Linked Issues check ✅ Passed The PR addresses issue #98 by implementing error handling in catch blocks via _debugWarn logging instead of leaving them empty, which satisfies the eslint no-empty rule requirement.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/social-share-button.js`:
- Around line 766-768: In _emit() in src/social-share-button.js the empty catch
blocks (around the DOM CustomEvent dispatch, the onAnalytics callback, and the
analyticsPlugins loop) should be replaced to surface errors when debugging:
catch the error as e and, if the component's debug flag (e.g. this.debug or
options.debug) is truthy, call console.warn with a descriptive message and the
caught error (e.g. "analytics event dispatch failed", "onAnalytics callback
failed", "analytics plugin failed") so analytics remain non-fatal but errors are
visible when debug is enabled; locate the three try/catch sites in _emit() and
implement the debug-conditional console.warn in each.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 71fe0743-af91-4bdc-b300-d02dd7630142

📥 Commits

Reviewing files that changed from the base of the PR and between 9e7e113 and 8bcc14c.

📒 Files selected for processing (1)
  • src/social-share-button.js

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/social-share-button.js`:
- Around line 708-717: The _debugWarn method lacks the concise inline comment
required by our JS rules; add a short inline comment inside the _debugWarn
function (above the if-check) that briefly states this helper logs analytics
warnings only in debug mode and intentionally uses console.warn for visibility
during development, while keeping the existing JSDoc unchanged; reference the
method name _debugWarn when making the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 86d3689a-5fa0-403b-89f3-881ada04c415

📥 Commits

Reviewing files that changed from the base of the PR and between 8bcc14c and 2340ded.

📒 Files selected for processing (1)
  • src/social-share-button.js

@krishnan05
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 14, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@kpj2006
Copy link
Contributor

kpj2006 commented Mar 17, 2026

@CodeRabbit as Console statements in production library code can pollute the browser console for end users and potentially leak internal error details.
similarily ig adding err in catch may also pollute the code.
if yes, what would be the preferred approach to solve this.
our actual issue is when we run npm run lint
it will show
social-share-button-aossie@1.0.3 lint
eslint src/**/*.{js,jsx} --max-warnings=0

/home/aayush-krishnan/Desktop/SocialShareButton/src/social-share-button.js
766:19 error Empty block statement no-empty
773:19 error Empty block statement no-empty
782:23 error Empty block statement no-empty

✖ 3 problems (3 errors, 0 warnings)

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

Tip

For best results, initiate chat on the files or code changes.

@kpj2006 Your concern is completely valid — unconditional console.warn/console.error in a distributed library can:

  1. Clutter every end-user's browser console even when everything is working as expected.
  2. Expose internal error details (stack traces, payload shapes, plugin names) that the library consumer didn't ask for.

Preferred approach: debug-gated _debugWarn helper

This is the pattern already applied in this PR, and it's the right one. Here's why it solves both problems simultaneously:

/**
 * Logs a warning message only when debug mode is enabled.
 * Analytics errors must never surface to end-users in production.
 *
 * `@param` {string} message - Human-readable description of the failure.
 * `@param` {Error}  err     - The caught error object for diagnostic context.
 */
_debugWarn(message, err) {
  if (this.options.debug) {
    // eslint-disable-next-line no-console
    console.warn(`[SocialShareButton] ${message}`, err);
  }
}

Then in each of the three catch blocks:

// Line ~766 — DOM CustomEvent dispatch
} catch (err) {
  this._debugWarn('Failed to dispatch analytics CustomEvent.', err);
}

// Line ~773 — onAnalytics callback
} catch (err) {
  this._debugWarn('onAnalytics callback threw an error.', err);
}

// Line ~782 — analyticsPlugins loop
} catch (err) {
  this._debugWarn('Analytics plugin track() failed.', err);
}

Why passing err is safe here

Scenario What happens
Production (debug not set / false) _debugWarn body never executes — err is never printed, nothing leaks.
Developer debugging (debug: true) Developer explicitly opted in; seeing the full error is exactly what they need.

The err object itself is just a local variable in the catch scope. It only reaches the console if this.options.debug === true, which is an explicit, opt-in choice by the library consumer. End users are never affected.


Why a bare comment is not enough

} catch (_) {
  // intentionally ignored
}

This does pass the no-empty lint rule, but it was flagged in earlier review discussions as too weak — it silently hides integration bugs (e.g., a misconfigured analytics plugin) and makes debugging very hard for contributors.


Summary

The _debugWarn approach is the canonical solution for this repo because it:

  • ✅ Fixes the three no-empty ESLint errors (catch blocks are no longer empty)
  • ✅ Keeps the no-console ESLint rule satisfied (violation is confined to one location with one disable comment)
  • ✅ Produces zero console output in production by default
  • ✅ Gives contributors a useful diagnostic tool when debug: true

✏️ Learnings added
Learnt from: kpj2006
URL: https://github.com/AOSSIE-Org/SocialShareButton/pull/99

Timestamp: 2026-03-17T20:18:01.332Z
Learning: In AOSSIE-Org/SocialShareButton, kpj2006 confirmed that bare console statements in library catch blocks are unacceptable in production because they pollute end-user browser consoles and can leak internal error details. The approved pattern is a debug-gated `_debugWarn(message, err)` private helper (single `eslint-disable-next-line no-console` comment inside it), called from catch blocks in `_emit()`. When `options.debug` is false (the production default), nothing is ever logged. Passing the `err` object to `_debugWarn` is explicitly safe under this pattern.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: kpj2006
Repo: AOSSIE-Org/SocialShareButton PR: 0
File: :0-0
Timestamp: 2026-03-10T07:25:17.136Z
Learning: For the AOSSIE-Org/SocialShareButton repository, kpj2006 wants contributors to add proper inline comments to all methods in library source files (especially src/social-share-button.js). The preferred enforcement mechanism is CodeRabbit path-based review instructions (skills) in .coderabbit.yaml rather than scripts or workflows. Flag any newly added or modified function that lacks a descriptive comment during reviews.

Learnt from: kpj2006
Repo: AOSSIE-Org/SocialShareButton PR: 0
File: :0-0
Timestamp: 2026-03-10T07:25:17.136Z
Learning: For the AOSSIE-Org/SocialShareButton repository, kpj2006 wants contributors to add proper inline comments to all methods in library source files (especially src/social-share-button.js). The preferred enforcement mechanism is CodeRabbit path-based review instructions (skills) in .coderabbit.yaml, rather than scripts or workflows. During reviews, flag any newly added or modified function that lacks a descriptive comment explaining what it does, why it exists, and its parameters/return values.

Learnt from: krishnan05
Repo: AOSSIE-Org/SocialShareButton PR: 99
File: src/social-share-button.js:766-768
Timestamp: 2026-03-13T19:38:54.290Z
Learning: In src/social-share-button.js, the ESLint config (eslint.config.js) already enforces "no-console": "error" (issue `#44` is closed). The existing debug console.log in _emit() uses an `// eslint-disable-next-line no-console` directive. For the catch blocks in _emit(), the recommended pattern is a private `_debugWarn(message, err)` helper method with a single eslint-disable-next-line comment, rather than adding inline console.warn calls with per-site eslint-disable comments. This keeps no-console violations contained to one location.

Learnt from: kpj2006
Repo: AOSSIE-Org/SocialShareButton PR: 65
File: src/social-share-button.js:753-763
Timestamp: 2026-03-12T19:22:19.186Z
Learning: In AOSSIE-Org/SocialShareButton (src/social-share-button.js), the empty catch blocks in `_emit()` around DOM CustomEvent dispatch, onAnalytics callback, and analyticsPlugins loop should be replaced with debug-conditional console.warn calls (e.g., `if (this.options.debug) { console.warn("[SocialShareButton Analytics] ...", err); }`). Analytics failures must remain non-fatal (never block the core share action), but empty catch blocks are considered too weak as they hide integration bugs and make debugging harder. A plain comment inside the catch is not sufficient — a conditional warning is preferred.

Learnt from: kpj2006
Repo: AOSSIE-Org/SocialShareButton PR: 0
File: :0-0
Timestamp: 2026-03-17T17:12:57.712Z
Learning: In AOSSIE-Org/SocialShareButton, new wrapper files (e.g., src/social-share-button-preact.jsx) added in a PR are not part of any CDN release until the next version tag is cut. When reviewing PRs that add new wrapper/source files, flag any README or index.html CDN URLs that reference a version predating the new file, and check that acquisition instructions (CDN URL, npm, or download link) are provided for the new file itself.

@kpj2006
Copy link
Contributor

kpj2006 commented Mar 17, 2026

@CodeRabbit could you check inside our repo is there any polluted code left?

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== All console.* usages in src/ ==="
rg -n --type=js --type=jsx -B3 -A1 'console\.' src/

echo ""
echo "=== Empty or near-empty catch blocks in src/ ==="
rg -n --type=js --type=jsx -A3 'catch\s*(\(' src/ | grep -A3 'catch'

echo ""
echo "=== _debugWarn usages ==="
rg -n --type=js --type=jsx -B2 -A2 '_debugWarn' src/

echo ""
echo "=== Raw catch blocks (show context) ==="
rg -nP --type=js 'catch\s*\(' src/ -A5

Length of output: 2010


🏁 Script executed:

#!/bin/bash
echo "=== All console.* usages in src/ (all files) ==="
rg -n -B3 -A2 'console\.' src/

echo ""
echo "=== All catch blocks in src/ (all files) ==="
rg -n 'catch\s*\(' src/ -A5

echo ""
echo "=== _debugWarn definition and all usages ==="
rg -n '_debugWarn' src/

echo ""
echo "=== List all source files ==="
fd . src/ --type f

Length of output: 3812


@kpj2006 Good news — the codebase is clean! Here's the full audit across all src/ files:


src/social-share-button.js — ✅ Clean

Line Statement Guard
717 console.warn(...) Inside _debugWarn()if (!this.options.debug) return; fires first + eslint-disable-next-line
763 console.log(...) Inside explicit if (this.options.debug) block + eslint-disable-next-line

Both are completely silent in production. Nothing leaks to end-user consoles unless the library consumer explicitly sets debug: true.


src/social-share-analytics.js — ✅ Clean

Line 26 contains console.log(e.detail) but it is inside a JSDoc block comment (a usage example for developers reading the docs), not executable runtime code. It is never evaluated by the browser.


src/social-share-button-react.jsx — ✅ Clean

No console.* calls found at all.


Catch blocks — ✅ All handled

Location Handler
Line 461 (clipboard .catch) Falls back to fallbackCopy() — no console
Line 501 (copy fallback) Sets button text to "Failed" — no console
Lines 778, 787, 798 (_emit analytics) All use this._debugWarn(...) — debug-gated

No polluted code remains. The _debugWarn pattern introduced in this PR has correctly contained all diagnostics behind the debug flag.


🧠 Learnings used
Learnt from: kpj2006
Repo: AOSSIE-Org/SocialShareButton PR: 0
File: :0-0
Timestamp: 2026-03-17T20:18:01.332Z
Learning: In AOSSIE-Org/SocialShareButton, kpj2006 confirmed that bare console statements in library catch blocks are unacceptable in production because they pollute end-user browser consoles and can leak internal error details. The approved pattern is a debug-gated `_debugWarn(message, err)` private helper (single `eslint-disable-next-line no-console` comment inside it), called from catch blocks in `_emit()`. When `options.debug` is false (the production default), nothing is ever logged. Passing the `err` object to `_debugWarn` is explicitly safe under this pattern.

Learnt from: kpj2006
Repo: AOSSIE-Org/SocialShareButton PR: 0
File: :0-0
Timestamp: 2026-03-10T07:25:17.136Z
Learning: For the AOSSIE-Org/SocialShareButton repository, kpj2006 wants contributors to add proper inline comments to all methods in library source files (especially src/social-share-button.js). The preferred enforcement mechanism is CodeRabbit path-based review instructions (skills) in .coderabbit.yaml rather than scripts or workflows. Flag any newly added or modified function that lacks a descriptive comment during reviews.

Learnt from: kpj2006
Repo: AOSSIE-Org/SocialShareButton PR: 0
File: :0-0
Timestamp: 2026-03-10T07:25:17.136Z
Learning: For the AOSSIE-Org/SocialShareButton repository, kpj2006 wants contributors to add proper inline comments to all methods in library source files (especially src/social-share-button.js). The preferred enforcement mechanism is CodeRabbit path-based review instructions (skills) in .coderabbit.yaml, rather than scripts or workflows. During reviews, flag any newly added or modified function that lacks a descriptive comment explaining what it does, why it exists, and its parameters/return values.

Learnt from: kpj2006
Repo: AOSSIE-Org/SocialShareButton PR: 65
File: src/social-share-button.js:753-763
Timestamp: 2026-03-12T19:22:19.186Z
Learning: In AOSSIE-Org/SocialShareButton (src/social-share-button.js), the empty catch blocks in `_emit()` around DOM CustomEvent dispatch, onAnalytics callback, and analyticsPlugins loop should be replaced with debug-conditional console.warn calls (e.g., `if (this.options.debug) { console.warn("[SocialShareButton Analytics] ...", err); }`). Analytics failures must remain non-fatal (never block the core share action), but empty catch blocks are considered too weak as they hide integration bugs and make debugging harder. A plain comment inside the catch is not sufficient — a conditional warning is preferred.

Learnt from: krishnan05
Repo: AOSSIE-Org/SocialShareButton PR: 99
File: src/social-share-button.js:766-768
Timestamp: 2026-03-13T19:38:54.290Z
Learning: In src/social-share-button.js, the ESLint config (eslint.config.js) already enforces "no-console": "error" (issue `#44` is closed). The existing debug console.log in _emit() uses an `// eslint-disable-next-line no-console` directive. For the catch blocks in _emit(), the recommended pattern is a private `_debugWarn(message, err)` helper method with a single eslint-disable-next-line comment, rather than adding inline console.warn calls with per-site eslint-disable comments. This keeps no-console violations contained to one location.

Learnt from: kpj2006
Repo: AOSSIE-Org/SocialShareButton PR: 0
File: :0-0
Timestamp: 2026-03-17T17:12:57.712Z
Learning: In AOSSIE-Org/SocialShareButton, new wrapper files (e.g., src/social-share-button-preact.jsx) added in a PR are not part of any CDN release until the next version tag is cut. When reviewing PRs that add new wrapper/source files, flag any README or index.html CDN URLs that reference a version predating the new file, and check that acquisition instructions (CDN URL, npm, or download link) are provided for the new file itself.

Copy link
Contributor

@kpj2006 kpj2006 left a comment

Choose a reason for hiding this comment

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

lgtm

@kpj2006 kpj2006 merged commit 4bc9bcc into AOSSIE-Org:main Mar 17, 2026
2 checks passed
@kpj2006
Copy link
Contributor

kpj2006 commented Mar 17, 2026

@krishnan05 thanks for contribution!!

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.

[BUG]: Lint fails on main due to empty catch blocks in analytics (eslint no-empty)

2 participants