Skip to content

Improvement: added error handling using try-catch#129

Open
Akshat0125 wants to merge 1 commit intoAOSSIE-Org:mainfrom
Akshat0125:error-handling-fix
Open

Improvement: added error handling using try-catch#129
Akshat0125 wants to merge 1 commit intoAOSSIE-Org:mainfrom
Akshat0125:error-handling-fix

Conversation

@Akshat0125
Copy link
Copy Markdown

@Akshat0125 Akshat0125 commented Mar 24, 2026

Addressed Issues:

Fixes #(issue number)

Screenshots/Recordings:

Additional Notes:

Checklist

  • My code follows the project's code style and conventions
  • I have made corresponding changes to the documentation
  • 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 Contributing Guidelines

⚠️ AI Notice - Important!

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.

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling in the social share button to gracefully manage invalid configurations and prevent operation interruptions.
    • Enhanced stability when sharing across different platforms and restricted contexts.
    • Strengthened fallback mechanism for link copying when primary methods are unavailable.
    • Better error logging to support troubleshooting of sharing and copying issues.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 24, 2026

Walkthrough

Error handling enhancements added to the social share button module. Multiple operations—container resolution, share URL computation, window navigation, and clipboard operations—are now wrapped in try/catch blocks with console error logging to prevent unhandled exceptions and provide better error visibility.

Changes

Cohort / File(s) Summary
Error Handling in Button Creation
src/social-share-button.js
createButton() now wraps container selector resolution in try/catch to gracefully handle invalid selectors and prevent constructor failures.
Error Handling in Share Operations
src/social-share-button.js
share(platform) adds try/catch around share URL encoding and navigation (both window.location.href for email and window.open() for other platforms) to suppress errors in restricted contexts.
Error Handling in Clipboard Operations
src/social-share-button.js
copyLink() and fallbackCopy() now wrap async clipboard writes and fallback copy attempts in try/catch blocks with improved error logging and state management.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

Typescript Lang

Suggested reviewers

  • kpj2006

Poem

🐰 Error handlers hop with glee,
Try and catch now set us free,
No more crashes, silent falls,
Graceful handling answers calls! 🌟

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: adding error handling using try-catch blocks throughout the codebase.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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
Copy Markdown
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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/social-share-button.js (1)

89-102: ⚠️ Potential issue | 🟠 Major

Abort init when container lookup fails.

The new catch sends invalid selectors down the same silent no-op path as a missing container: no button is mounted, but createModal() and attachEvents() still run. The React/Preact wrappers instantiate this constructor directly, so this becomes a silent initialization failure instead of a surfaced one. Have createButton() signal failure so init() can stop instead of continuing with an unusable instance.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/social-share-button.js` around lines 89 - 102, createButton() currently
swallows invalid container selector errors and continues, causing init() to
proceed to createModal() and attachEvents() on an unusable instance; change
createButton() to surface failure (either return null/false or rethrow the
caught error) when the container lookup fails, and update init() to check the
createButton() result and abort initialization (skip createModal() and
attachEvents() and propagate/throw the error) if creation failed; references:
createButton(), init(), createModal(), attachEvents(), and the class constructor
that calls init().
🤖 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 413-419: When URL generation or navigation fails in the share
flow, do not let the function continue to the success branch; inside the catch
blocks around this.getShareURL(platform) and the later navigation/open code,
emit the analytics event social_share_error (including the caught error message)
and return immediately to avoid running onShare or emitting social_share_success
or the "No share URL configured" branch; update the catch handlers that
currently log errors to call the analytics emitter (matching the payload shape
used in src/social-share-analytics.js) with event name social_share_error and
then return from the enclosing method instead of falling through.
- Around line 96-97: Replace all bare console.error calls in the catch blocks of
src/social-share-button.js with the library's debug-gated helper
`_debugWarn(message, err)` (or create it if missing) so logging is only emitted
when options.debug is truthy; specifically, change the catch in the DOM
container selector error (current catch around the "DOM manipulation failed:
Invalid container selector" message) and the other listed catch blocks (around
lines 417-418, 428-429, 435-436, 487-493, 531-532) to call `_debugWarn("...
descriptive message ...", error)` instead of console.error, and implement
`_debugWarn` as a private function that checks `options.debug` before calling
console.* to satisfy the `no-console` rule and match the approved pattern.

---

Outside diff comments:
In `@src/social-share-button.js`:
- Around line 89-102: createButton() currently swallows invalid container
selector errors and continues, causing init() to proceed to createModal() and
attachEvents() on an unusable instance; change createButton() to surface failure
(either return null/false or rethrow the caught error) when the container lookup
fails, and update init() to check the createButton() result and abort
initialization (skip createModal() and attachEvents() and propagate/throw the
error) if creation failed; references: createButton(), init(), createModal(),
attachEvents(), and the class constructor that calls init().
🪄 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: b6914224-ff68-4ad1-8640-1579f1b3b93e

📥 Commits

Reviewing files that changed from the base of the PR and between 18d0b97 and 6eaa24f.

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

Comment on lines +96 to +97
} catch (error) {
console.error("DOM manipulation failed: Invalid container selector", error);
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.

⚠️ Potential issue | 🟠 Major

Replace bare console.error calls with a debug-gated helper.

These catch blocks now write directly to consumers' browser consoles. In this repo that both violates the approved library logging pattern and trips the project's no-console rule; reuse or generalize a single private helper gated by options.debug instead.

Based on learnings: bare console statements in library catch blocks are unacceptable in production, the approved pattern is a debug-gated _debugWarn(message, err) helper, and eslint.config.js already enforces no-console: error.

Also applies to: 417-418, 428-429, 435-436, 487-493, 531-532

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/social-share-button.js` around lines 96 - 97, Replace all bare
console.error calls in the catch blocks of src/social-share-button.js with the
library's debug-gated helper `_debugWarn(message, err)` (or create it if
missing) so logging is only emitted when options.debug is truthy; specifically,
change the catch in the DOM container selector error (current catch around the
"DOM manipulation failed: Invalid container selector" message) and the other
listed catch blocks (around lines 417-418, 428-429, 435-436, 487-493, 531-532)
to call `_debugWarn("... descriptive message ...", error)` instead of
console.error, and implement `_debugWarn` as a private function that checks
`options.debug` before calling console.* to satisfy the `no-console` rule and
match the approved pattern.

Comment on lines +413 to +419
let shareUrl = "";
try {
// URL handling: encodeURIComponent may throw URIError on lone surrogates
shareUrl = this.getShareURL(platform);
} catch (error) {
console.error("URL handling failed: Data encoding error", error);
}
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.

⚠️ Potential issue | 🟠 Major

Do not report social_share_success after a caught share error.

If URL generation or navigation/open throws, the new catches swallow the failure and this method still falls through to either social_share_success or the generic "No share URL configured" branch. That makes the analytics payload incorrect relative to src/social-share-analytics.js:19-75, and onShare can run for a failed share. Emit social_share_error with the caught message and return from the catch path before the success/onShare branch.

Also applies to: 425-449

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/social-share-button.js` around lines 413 - 419, When URL generation or
navigation fails in the share flow, do not let the function continue to the
success branch; inside the catch blocks around this.getShareURL(platform) and
the later navigation/open code, emit the analytics event social_share_error
(including the caught error message) and return immediately to avoid running
onShare or emitting social_share_success or the "No share URL configured"
branch; update the catch handlers that currently log errors to call the
analytics emitter (matching the payload shape used in
src/social-share-analytics.js) with event name social_share_error and then
return from the enclosing method instead of falling through.

@krishnan05
Copy link
Copy Markdown
Contributor

krishnan05 commented Mar 26, 2026

@coderabbitai was adding try and catch necessary on every instance as in the PR, as per me it was not at every instance. Also check whether this issue was already resolved

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 26, 2026

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the current state of the main branch for error handling patterns
git log --oneline -20 origin/main

echo "=== Current error handling in main branch ==="
rg -n "try\s*\{|catch\s*\(" src/social-share-button.js -A2 -B2

echo "=== console.error usage ==="
rg -n "console\.(error|warn|log)" src/social-share-button.js

echo "=== fallbackCopy function ==="
ast-grep --pattern 'fallbackCopy($_) { $$$ }'

echo "=== copyLink function ==="
ast-grep --pattern 'copyLink() { $$$ }'

echo "=== share function ==="
ast-grep --pattern 'share($_) { $$$ }'

echo "=== createButton function ==="
ast-grep --pattern 'createButton() { $$$ }'

Length of output: 5283


🏁 Script executed:

#!/bin/bash
# Check if there are other PRs addressing error handling
gh pr list --repo AOSSIE-Org/SocialShareButton --state all --limit 30 | grep -i "error\|catch\|fix\|handling"

echo "=== PR `#129` diff ==="
gh pr diff 129 --repo AOSSIE-Org/SocialShareButton

Length of output: 6318


@krishnan05: Good questions. Here's a thorough breakdown based on examining both the PR diff and the current codebase state.


1. Was the issue already resolved?

Not fully. Before this PR, only fallbackCopy() had a pre-existing try/catch (caught as _err). The other locations (createButton, share, copyLink) had no error handling prior to this PR. So the concern is legitimately new work — but the question is whether every instance is actually warranted.


2. Are all try-catch blocks necessary?

Location Necessary? Reasoning
createButton()document.querySelector() ✅ Yes querySelector can legitimately throw a SyntaxError for invalid CSS selectors
share()getShareURL() / encodeURIComponent ⚠️ Marginal encodeURIComponent can technically throw a URIError on lone surrogates, but this is extremely rare for developer-supplied URLs
share()window.location.href = shareUrl ❌ No Assigning to window.location.href does not throw in practice — in restricted contexts it silently fails or is ignored by the browser
share()window.open(...) ❌ No Popup blockers return null, they do not throw. The try-catch here is based on a misconception and won't actually catch popup-blocking behavior
copyLink() outer try around navigator.clipboard.writeText() ⚠️ Redundant The .catch() handler immediately below already handles async rejections. Synchronous throws from writeText() are essentially theoretical
fallbackCopy() binding _errerror + logging ✅ Yes Renaming the catch variable and adding logging is a genuine improvement

The two most problematic additions are the window.location.href and window.open() wrappers — they are based on incorrect assumptions about what causes those APIs to throw.


3. Critical pattern violation

All new catch blocks use bare console.error(...), but this codebase has an established convention for error logging — the _debugWarn() helper — which is already used correctly in _emit():

// ✅ Correct pattern (already in the file)
} catch (err) {
  this._debugWarn("DOM event dispatch failed", err);
}

// ❌ Pattern used in this PR (violates project convention)
} catch (error) {
  console.error("Sharing failed: Popup window blocked", error);
}

Bare console.error calls in a library pollute end-user browser consoles and can leak internal details in production — the _debugWarn() approach only logs when options.debug is true.


Summary recommendation

This PR should be requested to change on the following grounds:

  1. Remove the try-catch around window.location.href and window.open() — these are unnecessary and based on incorrect assumptions.
  2. Replace all bare console.error(...) in catch blocks with this._debugWarn(...) to match the established codebase pattern.
  3. The outer synchronous try in copyLink() around the clipboard promise chain can be removed as redundant.

🧠 Learnings used
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-17T20:18:01.344Z
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.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 26, 2026

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check PR `#129` details and files changed
gh pr view 129 --repo AOSSIE-Org/SocialShareButton --json title,body,state,files

# Look for other PRs related to error handling
gh pr list --repo AOSSIE-Org/SocialShareButton --state all --search "error handling" --json number,title,state,mergedAt

# Check related issues
gh issue list --repo AOSSIE-Org/SocialShareButton --state all --search "error handling" --json number,title,state

Length of output: 5989


🏁 Script executed:

#!/bin/bash
# Check what PR `#99` changed (the already-merged error handling fix)
gh pr view 99 --repo AOSSIE-Org/SocialShareButton --json title,body,mergedAt

# Get the diff of PR `#129` to evaluate each try-catch
gh pr diff 129 --repo AOSSIE-Org/SocialShareButton

# Check current state of the main branch file
gh api repos/AOSSIE-Org/SocialShareButton/contents/src/social-share-button.js --jq '.content' | base64 -d | head -300

Length of output: 24433


@krishnan05 Great questions. Here's a detailed assessment:


1. Was this issue already resolved?

No — not by PR #99. PR #99 ("fix: avoid empty catch blocks in analytics", merged 2026-03-17) only addressed empty catch blocks inside the _emit() analytics method. PR #129 targets entirely different functions (createButton, share, copyLink, fallbackCopy), so there is no direct overlap or duplicate.


2. Was try-catch necessary at every instance?

Here's a breakdown of each addition:

Location Necessary? Reason
createButton()document.querySelector() ✅ Yes querySelector can throw a SyntaxError for invalid CSS selector strings — try-catch is appropriate here.
share()getShareURL() ⚠️ Marginal encodeURIComponent can theoretically throw a URIError for lone surrogates, but inputs come from window.location.href / document.title, which are extremely unlikely to contain invalid characters in practice.
share()window.location.href = shareUrl (email path) ❌ Unnecessary Assigning to window.location.href does not throw. Navigation restrictions produce silent no-ops or CSP errors — not exceptions catchable this way.
share()window.open() (other platforms) ❌ Unnecessary When blocked by a browser, window.open() returns null — it does not throw. A null-check (if (!window.open(...)) { ... }) would be the correct approach.
copyLink() → outer try-catch around navigator.clipboard.writeText() ❌ Unnecessary writeText() is async and returns a Promise — it never throws synchronously. The existing .catch() handler already covers async failures.
fallbackCopy() → rename _errerror + log ✅ Valid A reasonable improvement to the existing catch block.

3. Additional concern: bare console.error calls

All new catch blocks use bare console.error(...). Based on the established pattern for this repo (from previously merged PR #99 and the project's lint history), the approved approach is a debug-gated _debugWarn() helper, so that nothing is logged in production (options.debug === false). Bare console.error calls pollute end-user browser consoles and can expose internal details — this applies to all the catch blocks added in this PR.


Summary

The PR would benefit from being scoped down to only the genuinely useful additions (querySelector in createButton() and the fallbackCopy() improvement), removing the unnecessary try-catches around window.location.href, window.open(), and the synchronous wrapper around navigator.clipboard.writeText(), and replacing all bare console.error calls with the project's _debugWarn() pattern.


🧠 Learnings used
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-17T20:18:01.344Z
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.

@krishnan05
Copy link
Copy Markdown
Contributor

Tip

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

🧩 Analysis chain
🏁 Script executed:

#!/bin/bash
# Check PR `#129` details and files changed
gh pr view 129 --repo AOSSIE-Org/SocialShareButton --json title,body,state,files

# Look for other PRs related to error handling
gh pr list --repo AOSSIE-Org/SocialShareButton --state all --search "error handling" --json number,title,state,mergedAt

# Check related issues
gh issue list --repo AOSSIE-Org/SocialShareButton --state all --search "error handling" --json number,title,state

Length of output: 5989

🏁 Script executed:

#!/bin/bash
# Check what PR `#99` changed (the already-merged error handling fix)
gh pr view 99 --repo AOSSIE-Org/SocialShareButton --json title,body,mergedAt

# Get the diff of PR `#129` to evaluate each try-catch
gh pr diff 129 --repo AOSSIE-Org/SocialShareButton

# Check current state of the main branch file
gh api repos/AOSSIE-Org/SocialShareButton/contents/src/social-share-button.js --jq '.content' | base64 -d | head -300

Length of output: 24433

@krishnan05 Great questions. Here's a detailed assessment:

1. Was this issue already resolved?

No — not by PR #99. PR #99 ("fix: avoid empty catch blocks in analytics", merged 2026-03-17) only addressed empty catch blocks inside the _emit() analytics method. PR #129 targets entirely different functions (createButton, share, copyLink, fallbackCopy), so there is no direct overlap or duplicate.

2. Was try-catch necessary at every instance?

Here's a breakdown of each addition:

Location Necessary? Reason
createButton()document.querySelector() ✅ Yes querySelector can throw a SyntaxError for invalid CSS selector strings — try-catch is appropriate here.
share()getShareURL() ⚠️ Marginal encodeURIComponent can theoretically throw a URIError for lone surrogates, but inputs come from window.location.href / document.title, which are extremely unlikely to contain invalid characters in practice.
share()window.location.href = shareUrl (email path) ❌ Unnecessary Assigning to window.location.href does not throw. Navigation restrictions produce silent no-ops or CSP errors — not exceptions catchable this way.
share()window.open() (other platforms) ❌ Unnecessary When blocked by a browser, window.open() returns null — it does not throw. A null-check (if (!window.open(...)) { ... }) would be the correct approach.
copyLink() → outer try-catch around navigator.clipboard.writeText() ❌ Unnecessary writeText() is async and returns a Promise — it never throws synchronously. The existing .catch() handler already covers async failures.
fallbackCopy() → rename _errerror + log ✅ Valid A reasonable improvement to the existing catch block.

3. Additional concern: bare console.error calls

All new catch blocks use bare console.error(...). Based on the established pattern for this repo (from previously merged PR #99 and the project's lint history), the approved approach is a debug-gated _debugWarn() helper, so that nothing is logged in production (options.debug === false). Bare console.error calls pollute end-user browser consoles and can expose internal details — this applies to all the catch blocks added in this PR.

Summary

The PR would benefit from being scoped down to only the genuinely useful additions (querySelector in createButton() and the fallbackCopy() improvement), removing the unnecessary try-catches around window.location.href, window.open(), and the synchronous wrapper around navigator.clipboard.writeText(), and replacing all bare console.error calls with the project's _debugWarn() pattern.

🧠 Learnings used

@coderabbitai Please mark any redundant or unnecessary try-catch blocks directly in the review comments so the contributor can identify and address them.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 26, 2026

Tip

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

🧩 Analysis chain

Sure, @krishnan05! Let me fetch the exact diff line numbers and post inline review comments on the problematic try-catch blocks.


🏁 Script executed:

#!/bin/bash
# Get the full diff of PR `#129` with line numbers for inline commenting
gh pr diff 129 --repo AOSSIE-Org/SocialShareButton

echo "=== PR files changed ==="
gh pr view 129 --repo AOSSIE-Org/SocialShareButton --json files --jq '.files[].path'

echo "=== PR review comments already posted ==="
gh api repos/AOSSIE-Org/SocialShareButton/pulls/129/comments --jq '.[].body' 2>/dev/null | head -50

Length of output: 7813


Got the diff line numbers. Now I'll post the inline review comments on the three redundant try-catch blocks.


🏁 Script executed:

#!/bin/bash
# Get the head SHA of PR `#129`
HEAD_SHA=$(gh pr view 129 --repo AOSSIE-Org/SocialShareButton --json headRefOid --jq '.headRefOid')
echo "Head SHA: $HEAD_SHA"

# Post a review with inline comments on the redundant try-catch blocks
gh api repos/AOSSIE-Org/SocialShareButton/pulls/129/reviews \
  --method POST \
  --field commit_id="$HEAD_SHA" \
  --field event="COMMENT" \
  --field body="Flagging three try-catch blocks that are unnecessary based on how these browser APIs actually behave. See individual inline comments below." \
  --field 'comments=[
    {
      "path": "src/social-share-button.js",
      "line": 425,
      "side": "RIGHT",
      "body": "**❌ Redundant try-catch — `window.location.href` assignment does not throw.**\n\nAssigning to `window.location.href` does not raise a JavaScript exception. Navigation restrictions (e.g. CSP `frame-ancestors`, sandboxed iframes) produce browser-level silent no-ops or console warnings — they are **not** catchable via try-catch. This block gives a false sense of safety and should be removed entirely:\n\n```js\n// Remove the try/catch — simply assign directly:\nwindow.location.href = shareUrl;\n```"
    },
    {
      "path": "src/social-share-button.js",
      "line": 432,
      "side": "RIGHT",
      "body": "**❌ Redundant try-catch — `window.open()` does not throw when popup-blocked.**\n\nWhen a browser popup blocker intervenes, `window.open()` returns `null` — it does **not** throw an exception. This try-catch will never fire for the stated reason. The correct approach is a null-check on the return value:\n\n```js\n// Remove the try/catch; check the return value instead:\nconst opened = window.open(shareUrl, \"_blank\", \"noopener,noreferrer,width=600,height=600\");\nif (!opened) {\n  this._debugWarn(\"Popup window was blocked by the browser\");\n}\n```"
    },
    {
      "path": "src/social-share-button.js",
      "line": 459,
      "side": "RIGHT",
      "body": "**❌ Redundant outer try-catch — `navigator.clipboard.writeText()` never throws synchronously.**\n\n`writeText()` is an async method that returns a `Promise`. It cannot throw synchronously, so this outer try block will never catch anything. The existing `.catch((error) => { ... })` handler immediately below already covers all async failures. Remove the outer try-catch wrapper and keep only the promise chain:\n\n```js\n// Remove the outer try/catch — the .catch() already handles all failures:\nnavigator.clipboard\n  .writeText(this.options.url)\n  .then(() => { ... })\n  .catch((error) => {\n    this._debugWarn(\"Clipboard async write failed\", error);\n    this.fallbackCopy(input, copyBtn);\n  });\n```"
    }
  ]'

Length of output: 271


The review endpoint returned 403. Let me try posting individual inline diff comments directly.


🏁 Script executed:

#!/bin/bash
HEAD_SHA="6eaa24fb5c9cd14b6e2e659c14bfcbfa426944d6"

# Try posting individual pull request review comments (single comment endpoint)
echo "=== Posting comment 1: window.location.href try-catch ==="
gh api repos/AOSSIE-Org/SocialShareButton/pulls/129/comments \
  --method POST \
  --field commit_id="$HEAD_SHA" \
  --field path="src/social-share-button.js" \
  --field line=425 \
  --field side="RIGHT" \
  --field body="**❌ Redundant try-catch — \`window.location.href\` assignment does not throw.**

Assigning to \`window.location.href\` does not raise a JavaScript exception. Navigation restrictions (e.g. CSP \`frame-ancestors\`, sandboxed iframes) produce browser-level silent no-ops — they are **not** catchable via try-catch. This block gives a false sense of safety and should be removed:

\`\`\`js
// Simply assign directly — no try/catch needed:
window.location.href = shareUrl;
\`\`\`"

echo "=== Posting comment 2: window.open() try-catch ==="
gh api repos/AOSSIE-Org/SocialShareButton/pulls/129/comments \
  --method POST \
  --field commit_id="$HEAD_SHA" \
  --field path="src/social-share-button.js" \
  --field line=432 \
  --field side="RIGHT" \
  --field body="**❌ Redundant try-catch — \`window.open()\` does not throw when popup-blocked.**

When a popup blocker intervenes, \`window.open()\` returns \`null\` — it does **not** throw an exception. This try-catch will never catch a popup-blocked scenario. The correct fix is a null-check on the return value:

\`\`\`js
// Remove the try/catch; check the return value instead:
const opened = window.open(shareUrl, \"_blank\", \"noopener,noreferrer,width=600,height=600\");
if (!opened) {
  this._debugWarn(\"Popup window was blocked by the browser\");
}
\`\`\`"

echo "=== Posting comment 3: outer try-catch around navigator.clipboard.writeText() ==="
gh api repos/AOSSIE-Org/SocialShareButton/pulls/129/comments \
  --method POST \
  --field commit_id="$HEAD_SHA" \
  --field path="src/social-share-button.js" \
  --field line=459 \
  --field side="RIGHT" \
  --field body="**❌ Redundant outer try-catch — \`navigator.clipboard.writeText()\` never throws synchronously.**

\`writeText()\` is an async method returning a \`Promise\`. It cannot throw synchronously, so this outer try block can never catch anything. The existing \`.catch()\` handler immediately inside already handles all async failures. Remove the outer try-catch and keep only the promise chain:

\`\`\`js
// Remove outer try/catch — .catch() already handles all failures:
navigator.clipboard
  .writeText(this.options.url)
  .then(() => { /* ... */ })
  .catch((error) => {
    this._debugWarn(\"Clipboard async write failed\", error);
    this.fallbackCopy(input, copyBtn);
  });
\`\`\`"

Length of output: 880


@krishnan05, unfortunately the GitHub integration token doesn't have the permissions needed to post inline diff comments on this repository (both endpoints return 403 Resource not accessible by integration). Here are the three redundant try-catch blocks with their exact line numbers so you or the contributor can act on them directly:


❌ Line 425 — window.location.href try-catch (share(), email path)

Why redundant: Assigning to window.location.href does not throw a JavaScript exception. Navigation restrictions (e.g. CSP frame-ancestors, sandboxed iframes) result in browser-level silent no-ops — they are not catchable via try-catch.

// Remove the try/catch — simply assign directly:
window.location.href = shareUrl;

❌ Line 432 — window.open() try-catch (share(), other platforms)

Why redundant: Popup blockers cause window.open() to return null — they do not throw an exception. This try-catch can never fire for its stated purpose. The correct approach is a null-check:

// Remove the try/catch; check the return value instead:
const opened = window.open(shareUrl, "_blank", "noopener,noreferrer,width=600,height=600");
if (!opened) {
  this._debugWarn("Popup window was blocked by the browser");
}

❌ Line 459 — Outer try wrapping navigator.clipboard.writeText() (copyLink())

Why redundant: writeText() is async and returns a Promise — it cannot throw synchronously. The existing .catch() handler already handles all async failures. The outer try-catch is dead code:

// Remove the outer try/catch — .catch() already handles all failures:
navigator.clipboard
  .writeText(this.options.url)
  .then(() => { /* ... */ })
  .catch((error) => {
    this._debugWarn("Clipboard async write failed", error);
    this.fallbackCopy(input, copyBtn);
  });

Additionally, all the catch blocks in this PR use bare console.error(...), which violates the project's established _debugWarn() pattern and will trip the no-console ESLint rule. Every catch block's logging should be replaced with this._debugWarn("...", error) calls instead.


🧠 Learnings used
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-17T20:18:01.344Z
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: 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-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: SIDDHANTCOOKIE
Repo: AOSSIE-Org/SocialShareButton PR: 117
File: .github/workflows/sync-pr-labels.yml:159-172
Timestamp: 2026-03-20T20:22:01.941Z
Learning: In AOSSIE-Org/SocialShareButton PR `#117`, the overlapping file-based label mappings in `.github/workflows/sync-pr-labels.yml` (e.g., `.github/workflows/*.yml` triggering `configuration`, `github-actions`, and `ci-cd` simultaneously; `.jsx` triggering both `javascript` and `frontend`) are **intentional**. The design goal is comprehensive visibility — multiple labels are applied on purpose so maintainers can see all relevant categories a PR touches. Do not flag these overlaps as bugs or recommend exclusions/priority systems.

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.

@krishnan05
Copy link
Copy Markdown
Contributor

@Akshat0125 please update the PR as per CodeRabbit’s review, specifically removing redundant try-catch blocks as makred by coderabbit (e.g., around window.open, window.location, and the outer clipboard wrapper) and replacing all console usage with the _debugWarn pattern.

You can refer to the earlier implementation( #99 ) where _debugWarn was introduced—logging should be debug-gated and not use direct console.*.

Also, it would be better to open an issue first so the scope is properly documented and tracked, and then align the PR accordingly.

@coderabbitai please open an issue outlining error handling improvements and clearly identifying where try-catch is actually necessary.
(cc: @kpj2006 .

@krishnan05
Copy link
Copy Markdown
Contributor

krishnan05 commented Mar 26, 2026

Tip

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

🧩 Analysis chain
Sure, @krishnan05! Let me fetch the exact diff line numbers and post inline review comments on the problematic try-catch blocks.

🏁 Script executed:

#!/bin/bash
# Get the full diff of PR `#129` with line numbers for inline commenting
gh pr diff 129 --repo AOSSIE-Org/SocialShareButton

echo "=== PR files changed ==="
gh pr view 129 --repo AOSSIE-Org/SocialShareButton --json files --jq '.files[].path'

echo "=== PR review comments already posted ==="
gh api repos/AOSSIE-Org/SocialShareButton/pulls/129/comments --jq '.[].body' 2>/dev/null | head -50

Length of output: 7813

Got the diff line numbers. Now I'll post the inline review comments on the three redundant try-catch blocks.

🏁 Script executed:

#!/bin/bash
# Get the head SHA of PR `#129`
HEAD_SHA=$(gh pr view 129 --repo AOSSIE-Org/SocialShareButton --json headRefOid --jq '.headRefOid')
echo "Head SHA: $HEAD_SHA"

# Post a review with inline comments on the redundant try-catch blocks
gh api repos/AOSSIE-Org/SocialShareButton/pulls/129/reviews \
  --method POST \
  --field commit_id="$HEAD_SHA" \
  --field event="COMMENT" \
  --field body="Flagging three try-catch blocks that are unnecessary based on how these browser APIs actually behave. See individual inline comments below." \
  --field 'comments=[
    {
      "path": "src/social-share-button.js",
      "line": 425,
      "side": "RIGHT",
      "body": "**❌ Redundant try-catch — `window.location.href` assignment does not throw.**\n\nAssigning to `window.location.href` does not raise a JavaScript exception. Navigation restrictions (e.g. CSP `frame-ancestors`, sandboxed iframes) produce browser-level silent no-ops or console warnings — they are **not** catchable via try-catch. This block gives a false sense of safety and should be removed entirely:\n\n```js\n// Remove the try/catch — simply assign directly:\nwindow.location.href = shareUrl;\n```"
    },
    {
      "path": "src/social-share-button.js",
      "line": 432,
      "side": "RIGHT",
      "body": "**❌ Redundant try-catch — `window.open()` does not throw when popup-blocked.**\n\nWhen a browser popup blocker intervenes, `window.open()` returns `null` — it does **not** throw an exception. This try-catch will never fire for the stated reason. The correct approach is a null-check on the return value:\n\n```js\n// Remove the try/catch; check the return value instead:\nconst opened = window.open(shareUrl, \"_blank\", \"noopener,noreferrer,width=600,height=600\");\nif (!opened) {\n  this._debugWarn(\"Popup window was blocked by the browser\");\n}\n```"
    },
    {
      "path": "src/social-share-button.js",
      "line": 459,
      "side": "RIGHT",
      "body": "**❌ Redundant outer try-catch — `navigator.clipboard.writeText()` never throws synchronously.**\n\n`writeText()` is an async method that returns a `Promise`. It cannot throw synchronously, so this outer try block will never catch anything. The existing `.catch((error) => { ... })` handler immediately below already covers all async failures. Remove the outer try-catch wrapper and keep only the promise chain:\n\n```js\n// Remove the outer try/catch — the .catch() already handles all failures:\nnavigator.clipboard\n  .writeText(this.options.url)\n  .then(() => { ... })\n  .catch((error) => {\n    this._debugWarn(\"Clipboard async write failed\", error);\n    this.fallbackCopy(input, copyBtn);\n  });\n```"
    }
  ]'

Length of output: 271

The review endpoint returned 403. Let me try posting individual inline diff comments directly.

🏁 Script executed:

#!/bin/bash
HEAD_SHA="6eaa24fb5c9cd14b6e2e659c14bfcbfa426944d6"

# Try posting individual pull request review comments (single comment endpoint)
echo "=== Posting comment 1: window.location.href try-catch ==="
gh api repos/AOSSIE-Org/SocialShareButton/pulls/129/comments \
  --method POST \
  --field commit_id="$HEAD_SHA" \
  --field path="src/social-share-button.js" \
  --field line=425 \
  --field side="RIGHT" \
  --field body="**❌ Redundant try-catch — \`window.location.href\` assignment does not throw.**

Assigning to \`window.location.href\` does not raise a JavaScript exception. Navigation restrictions (e.g. CSP \`frame-ancestors\`, sandboxed iframes) produce browser-level silent no-ops — they are **not** catchable via try-catch. This block gives a false sense of safety and should be removed:

\`\`\`js
// Simply assign directly — no try/catch needed:
window.location.href = shareUrl;
\`\`\`"

echo "=== Posting comment 2: window.open() try-catch ==="
gh api repos/AOSSIE-Org/SocialShareButton/pulls/129/comments \
  --method POST \
  --field commit_id="$HEAD_SHA" \
  --field path="src/social-share-button.js" \
  --field line=432 \
  --field side="RIGHT" \
  --field body="**❌ Redundant try-catch — \`window.open()\` does not throw when popup-blocked.**

When a popup blocker intervenes, \`window.open()\` returns \`null\` — it does **not** throw an exception. This try-catch will never catch a popup-blocked scenario. The correct fix is a null-check on the return value:

\`\`\`js
// Remove the try/catch; check the return value instead:
const opened = window.open(shareUrl, \"_blank\", \"noopener,noreferrer,width=600,height=600\");
if (!opened) {
  this._debugWarn(\"Popup window was blocked by the browser\");
}
\`\`\`"

echo "=== Posting comment 3: outer try-catch around navigator.clipboard.writeText() ==="
gh api repos/AOSSIE-Org/SocialShareButton/pulls/129/comments \
  --method POST \
  --field commit_id="$HEAD_SHA" \
  --field path="src/social-share-button.js" \
  --field line=459 \
  --field side="RIGHT" \
  --field body="**❌ Redundant outer try-catch — \`navigator.clipboard.writeText()\` never throws synchronously.**

\`writeText()\` is an async method returning a \`Promise\`. It cannot throw synchronously, so this outer try block can never catch anything. The existing \`.catch()\` handler immediately inside already handles all async failures. Remove the outer try-catch and keep only the promise chain:

\`\`\`js
// Remove outer try/catch — .catch() already handles all failures:
navigator.clipboard
  .writeText(this.options.url)
  .then(() => { /* ... */ })
  .catch((error) => {
    this._debugWarn(\"Clipboard async write failed\", error);
    this.fallbackCopy(input, copyBtn);
  });
\`\`\`"

Length of output: 880

@krishnan05, unfortunately the GitHub integration token doesn't have the permissions needed to post inline diff comments on this repository (both endpoints return 403 Resource not accessible by integration). Here are the three redundant try-catch blocks with their exact line numbers so you or the contributor can act on them directly:

❌ Line 425 — window.location.href try-catch (share(), email path)

Why redundant: Assigning to window.location.href does not throw a JavaScript exception. Navigation restrictions (e.g. CSP frame-ancestors, sandboxed iframes) result in browser-level silent no-ops — they are not catchable via try-catch.

// Remove the try/catch — simply assign directly:
window.location.href = shareUrl;

❌ Line 432 — window.open() try-catch (share(), other platforms)

Why redundant: Popup blockers cause window.open() to return null — they do not throw an exception. This try-catch can never fire for its stated purpose. The correct approach is a null-check:

// Remove the try/catch; check the return value instead:
const opened = window.open(shareUrl, "_blank", "noopener,noreferrer,width=600,height=600");
if (!opened) {
  this._debugWarn("Popup window was blocked by the browser");
}

❌ Line 459 — Outer try wrapping navigator.clipboard.writeText() (copyLink())

Why redundant: writeText() is async and returns a Promise — it cannot throw synchronously. The existing .catch() handler already handles all async failures. The outer try-catch is dead code:

// Remove the outer try/catch — .catch() already handles all failures:
navigator.clipboard
  .writeText(this.options.url)
  .then(() => { /* ... */ })
  .catch((error) => {
    this._debugWarn("Clipboard async write failed", error);
    this.fallbackCopy(input, copyBtn);
  });

Additionally, all the catch blocks in this PR use bare console.error(...), which violates the project's established _debugWarn() pattern and will trip the no-console ESLint rule. Every catch block's logging should be replaced with this._debugWarn("...", error) calls instead.

🧠 Learnings used

@Akshat0125. Also link the issue created by coderabbit in this PR and read contributing.md. Join discord sever and give updates there

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 26, 2026

Tip

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

🧩 Analysis chain

Sure, @krishnan05! Let me open the issue now.


🏁 Script executed:

#!/bin/bash
gh issue create \
  --repo AOSSIE-Org/SocialShareButton \
  --title "Improvement: Targeted error handling in createButton(), share(), copyLink(), and fallbackCopy()" \
  --assignee krishnan05 \
  --body "## Overview

PR `#129` added try-catch blocks across several methods in \`src/social-share-button.js\`. After review, some additions are well-founded while others are based on incorrect assumptions about browser API behaviour. This issue documents which changes are necessary, which should be removed, and the correct logging pattern to use throughout.

**Requested by:** `@krishnan05`
**Related PR:** https://github.com/AOSSIE-Org/SocialShareButton/pull/129
**Reference comment:** https://github.com/AOSSIE-Org/SocialShareButton/pull/129#issuecomment-2762048660

---

## ✅ Try-catch blocks that ARE necessary

### 1. \`createButton()\` → \`document.querySelector()\`
\`querySelector()\` throws a \`SyntaxError\` when passed an invalid CSS selector string. Since the selector is user-supplied via \`options.container\`, a try-catch here is appropriate defensive programming.

### 2. \`fallbackCopy()\` → rename \`_err\` → \`error\` and add logging
The existing catch block silently swallows errors. Binding the error variable and logging it through the debug-gated \`_debugWarn()\` helper is a valid improvement.

---

## ❌ Try-catch blocks that are NOT necessary (should be removed)

### 3. \`share()\` → \`window.location.href = shareUrl\` (email path)
Assigning to \`window.location.href\` does **not** throw a JavaScript exception. Navigation restrictions (e.g. CSP \`frame-ancestors\`, sandboxed iframes) result in browser-level silent no-ops — they are not catchable via try-catch. **Remove the try-catch and assign directly.**

### 4. \`share()\` → \`window.open(shareUrl, ...)\` (other platforms)
When a popup blocker intervenes, \`window.open()\` returns \`null\` — it does **not** throw an exception. The try-catch will never fire for the stated reason. **The correct fix is a null-check on the return value:**

\`\`\`js
const opened = window.open(shareUrl, '_blank', 'noopener,noreferrer,width=600,height=600');
if (!opened) {
  this._debugWarn('Popup window was blocked by the browser');
}
\`\`\`

### 5. \`copyLink()\` → outer \`try\` wrapping \`navigator.clipboard.writeText()\`
\`writeText()\` is an async method that returns a \`Promise\`. It cannot throw synchronously, so the outer try block will never catch anything. The existing \`.catch()\` handler on the promise chain already covers all async failures. **Remove the outer try-catch wrapper.**

---

## ⚠️ Logging pattern violation

All new catch blocks introduced in PR `#129` use bare \`console.error(...)\`. This violates the project's established convention and will fail the \`no-console\` ESLint rule (enforced since issue `#44`).

**Required pattern** (introduced in PR `#99`):

\`\`\`js
// ✅ Correct — debug-gated, no console pollution in production:
} catch (err) {
  this._debugWarn('Descriptive message about what failed', err);
}
\`\`\`

When \`options.debug\` is \`false\` (the production default), nothing is logged. Every catch block in this PR must be updated to use \`this._debugWarn()\` instead of \`console.error()\`.

---

## Acceptance Criteria

- [ ] Remove try-catch around \`window.location.href\` assignment in \`share()\`
- [ ] Replace try-catch around \`window.open()\` in \`share()\` with a null-check on the return value
- [ ] Remove outer synchronous try-catch wrapper in \`copyLink()\` around the clipboard promise chain
- [ ] Replace all \`console.error(...)\` calls in catch blocks with \`this._debugWarn(...)\`
- [ ] Keep the try-catch in \`createButton()\` around \`document.querySelector()\` (with \`_debugWarn\` logging)
- [ ] Keep the \`fallbackCopy()\` catch block improvement (with \`_debugWarn\` logging)
"

Length of output: 45


The assignee lookup failed. Retrying without the --assignee flag.


🏁 Script executed:

#!/bin/bash
gh issue create \
  --repo AOSSIE-Org/SocialShareButton \
  --title "Improvement: Targeted error handling in createButton(), share(), copyLink(), and fallbackCopy()" \
  --body "## Overview

PR `#129` added try-catch blocks across several methods in \`src/social-share-button.js\`. After review, some additions are well-founded while others are based on incorrect assumptions about browser API behaviour. This issue documents which changes are necessary, which should be removed, and the correct logging pattern to use throughout.

**Requested by:** `@krishnan05`
**Related PR:** https://github.com/AOSSIE-Org/SocialShareButton/pull/129
**Reference comment:** https://github.com/AOSSIE-Org/SocialShareButton/pull/129#issuecomment-2762048660

---

## ✅ Try-catch blocks that ARE necessary

### 1. \`createButton()\` → \`document.querySelector()\`
\`querySelector()\` throws a \`SyntaxError\` when passed an invalid CSS selector string. Since the selector is user-supplied via \`options.container\`, a try-catch here is appropriate defensive programming.

### 2. \`fallbackCopy()\` → rename \`_err\` → \`error\` and add logging
The existing catch block silently swallows errors. Binding the error variable and logging it through the debug-gated \`_debugWarn()\` helper is a valid improvement.

---

## ❌ Try-catch blocks that are NOT necessary (should be removed)

### 3. \`share()\` → \`window.location.href = shareUrl\` (email path)
Assigning to \`window.location.href\` does **not** throw a JavaScript exception. Navigation restrictions (e.g. CSP \`frame-ancestors\`, sandboxed iframes) result in browser-level silent no-ops — they are not catchable via try-catch. **Remove the try-catch and assign directly.**

### 4. \`share()\` → \`window.open(shareUrl, ...)\` (other platforms)
When a popup blocker intervenes, \`window.open()\` returns \`null\` — it does **not** throw an exception. The try-catch will never fire for the stated reason. **The correct fix is a null-check on the return value:**

\`\`\`js
const opened = window.open(shareUrl, '_blank', 'noopener,noreferrer,width=600,height=600');
if (!opened) {
  this._debugWarn('Popup window was blocked by the browser');
}
\`\`\`

### 5. \`copyLink()\` → outer \`try\` wrapping \`navigator.clipboard.writeText()\`
\`writeText()\` is an async method that returns a \`Promise\`. It cannot throw synchronously, so the outer try block will never catch anything. The existing \`.catch()\` handler on the promise chain already covers all async failures. **Remove the outer try-catch wrapper.**

---

## ⚠️ Logging pattern violation

All new catch blocks introduced in PR `#129` use bare \`console.error(...)\`. This violates the project's established convention and will fail the \`no-console\` ESLint rule (enforced since issue `#44`).

**Required pattern** (introduced in PR `#99`):

\`\`\`js
// ✅ Correct — debug-gated, no console pollution in production:
} catch (err) {
  this._debugWarn('Descriptive message about what failed', err);
}
\`\`\`

When \`options.debug\` is \`false\` (the production default), nothing is logged. Every catch block in this PR must be updated to use \`this._debugWarn()\` instead of \`console.error()\`.

---

## Acceptance Criteria

- [ ] Remove try-catch around \`window.location.href\` assignment in \`share()\`
- [ ] Replace try-catch around \`window.open()\` in \`share()\` with a null-check on the return value
- [ ] Remove outer synchronous try-catch wrapper in \`copyLink()\` around the clipboard promise chain
- [ ] Replace all \`console.error(...)\` calls in catch blocks with \`this._debugWarn(...)\`
- [ ] Keep the try-catch in \`createButton()\` around \`document.querySelector()\` (with \`_debugWarn\` logging)
- [ ] Keep the \`fallbackCopy()\` catch block improvement (with \`_debugWarn\` logging)
"

Length of output: 58


@krishnan05 The issue has been created: #132

It covers:

  • Necessary try-catch blocks — document.querySelector() in createButton() and the fallbackCopy() catch block improvement.
  • Redundant try-catch blocks — window.location.href, window.open(), and the outer synchronous wrapper in copyLink() — along with the rationale for why each one should be removed or replaced.
  • ⚠️ Logging pattern — all console.error calls must be replaced with this._debugWarn() to comply with the project's established pattern and the no-console ESLint rule.

@Akshat0125 can align the PR against this issue's acceptance criteria before it's reviewed again.


🧠 Learnings used
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-17T20:18:01.344Z
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: 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-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: 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.

Learnt from: SIDDHANTCOOKIE
Repo: AOSSIE-Org/SocialShareButton PR: 117
File: .github/workflows/sync-pr-labels.yml:159-172
Timestamp: 2026-03-20T20:22:01.941Z
Learning: In AOSSIE-Org/SocialShareButton PR `#117`, the overlapping file-based label mappings in `.github/workflows/sync-pr-labels.yml` (e.g., `.github/workflows/*.yml` triggering `configuration`, `github-actions`, and `ci-cd` simultaneously; `.jsx` triggering both `javascript` and `frontend`) are **intentional**. The design goal is comprehensive visibility — multiple labels are applied on purpose so maintainers can see all relevant categories a PR touches. Do not flag these overlaps as bugs or recommend exclusions/priority systems.

Learnt from: SIDDHANTCOOKIE
Repo: AOSSIE-Org/SocialShareButton PR: 117
File: .github/workflows/sync-pr-labels.yml:108-124
Timestamp: 2026-03-20T20:21:08.219Z
Learning: In AOSSIE-Org/SocialShareButton's `.github/workflows/sync-pr-labels.yml` (PR `#117`), issue-derived labels are intentionally NOT removed when a PR's issue link is removed. The rationale is that the GitHub API cannot differentiate between labels auto-copied from a linked issue and labels manually added by a maintainer, so it is safer to leave them for a human to decide relevance. Do not flag this as a bug or suggest automatic removal of issue-derived labels in future reviews.

@krishnan05
Copy link
Copy Markdown
Contributor

@coderabbitai Remove not necessary part in the issue #132

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 26, 2026

Tip

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

🧩 Analysis chain

Sure, @krishnan05! Let me fetch the current issue body and remove the unnecessary sections.


🏁 Script executed:

#!/bin/bash
# Fetch current issue `#132` body
gh issue view 132 --repo AOSSIE-Org/SocialShareButton --json number,title,body

echo "=== Current issue body ==="
gh issue view 132 --repo AOSSIE-Org/SocialShareButton --json body --jq '.body'

Length of output: 7249


Got the full issue body. Now I'll update it to remove the ❌ section and the corresponding acceptance criteria items.


🏁 Script executed:

#!/bin/bash
gh issue edit 132 \
  --repo AOSSIE-Org/SocialShareButton \
  --body "## Overview

This issue tracks the error handling improvements needed in \`src/social-share-button.js\`, covering where try-catch blocks are necessary and the correct logging pattern to use.

**Requested by:** `@krishnan05`
**Related PR:** https://github.com/AOSSIE-Org/SocialShareButton/pull/129
**Reference comment:** https://github.com/AOSSIE-Org/SocialShareButton/pull/129#issuecomment-2762048660

---

## ✅ Try-catch blocks that ARE necessary

### 1. \`createButton()\` → \`document.querySelector()\`
\`querySelector()\` throws a \`SyntaxError\` when passed an invalid CSS selector string. Since the selector is user-supplied via \`options.container\`, a try-catch here is appropriate defensive programming.

### 2. \`fallbackCopy()\` → rename \`_err\` → \`error\` and add logging
The existing catch block silently swallows errors. Binding the error variable and logging it through the debug-gated \`_debugWarn()\` helper is a valid improvement.

---

## ⚠️ Logging pattern

All catch blocks must use the project's established debug-gated helper rather than bare \`console.error(...)\`, which violates the \`no-console\` ESLint rule (enforced since issue `#44`).

**Required pattern** (introduced in PR `#99`):

\`\`\`js
// ✅ Correct — debug-gated, no console pollution in production:
} catch (err) {
  this._debugWarn('Descriptive message about what failed', err);
}
\`\`\`

When \`options.debug\` is \`false\` (the production default), nothing is logged. Every catch block must use \`this._debugWarn()\` instead of \`console.error()\`.

---

## Acceptance Criteria

- [ ] Add try-catch in \`createButton()\` around \`document.querySelector()\` with \`_debugWarn\` logging
- [ ] Improve \`fallbackCopy()\` catch block: bind the error variable and log via \`_debugWarn\`
- [ ] Replace all \`console.error(...)\` calls in catch blocks with \`this._debugWarn(...)\`
"

Length of output: 163


@krishnan05, unfortunately the integration token doesn't have permission to edit issues on this repository (same 403 limitation we hit with inline PR comments). Here is the cleaned-up body you can paste directly into issue #132 via the GitHub UI (Edit button on the issue):


Updated issue body (copy-paste into #132):

## Overview

This issue tracks the error handling improvements needed in `src/social-share-button.js`, covering where try-catch blocks are necessary and the correct logging pattern to use.

**Requested by:** `@krishnan05`
**Related PR:** https://github.com/AOSSIE-Org/SocialShareButton/pull/129
**Reference comment:** https://github.com/AOSSIE-Org/SocialShareButton/pull/129#issuecomment-2762048660

---

## ✅ Try-catch blocks that ARE necessary

### 1. `createButton()``document.querySelector()`
`querySelector()` throws a `SyntaxError` when passed an invalid CSS selector string. Since the selector is user-supplied via `options.container`, a try-catch here is appropriate defensive programming.

### 2. `fallbackCopy()` → rename `_err``error` and add logging
The existing catch block silently swallows errors. Binding the error variable and logging it through the debug-gated `_debugWarn()` helper is a valid improvement.

---

## ⚠️ Logging pattern

All catch blocks must use the project's established debug-gated helper rather than bare `console.error(...)`, which violates the `no-console` ESLint rule (enforced since issue `#44`).

**Required pattern** (introduced in PR `#99`):

```js
// ✅ Correct — debug-gated, no console pollution in production:
} catch (err) {
  this._debugWarn('Descriptive message about what failed', err);
}

When options.debug is false (the production default), nothing is logged. Every catch block must use this._debugWarn() instead of console.error().


Acceptance Criteria

  • Add try-catch in createButton() around document.querySelector() with _debugWarn logging
  • Improve fallbackCopy() catch block: bind the error variable and log via _debugWarn
  • Replace all console.error(...) calls in catch blocks with this._debugWarn(...)

---

The changes remove the entire **❌ "Try-catch blocks that are NOT necessary"** section (items 3–5) and the three corresponding acceptance criteria items that referenced removing/replacing `window.location.href`, `window.open()`, and the clipboard wrapper. The issue now focuses solely on what needs to be **added or improved**.

---

<details>
<summary>🧠 Learnings used</summary>

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-17T20:18:01.344Z
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: 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-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: 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.


---

Learnt from: SIDDHANTCOOKIE
Repo: AOSSIE-Org/SocialShareButton PR: 117
File: .github/workflows/sync-pr-labels.yml:159-172
Timestamp: 2026-03-20T20:22:01.941Z
Learning: In AOSSIE-Org/SocialShareButton PR #117, the overlapping file-based label mappings in .github/workflows/sync-pr-labels.yml (e.g., .github/workflows/*.yml triggering configuration, github-actions, and ci-cd simultaneously; .jsx triggering both javascript and frontend) are intentional. The design goal is comprehensive visibility — multiple labels are applied on purpose so maintainers can see all relevant categories a PR touches. Do not flag these overlaps as bugs or recommend exclusions/priority systems.


---

Learnt from: SIDDHANTCOOKIE
Repo: AOSSIE-Org/SocialShareButton PR: 117
File: .github/workflows/sync-pr-labels.yml:108-124
Timestamp: 2026-03-20T20:21:08.219Z
Learning: In AOSSIE-Org/SocialShareButton's .github/workflows/sync-pr-labels.yml (PR #117), issue-derived labels are intentionally NOT removed when a PR's issue link is removed. The rationale is that the GitHub API cannot differentiate between labels auto-copied from a linked issue and labels manually added by a maintainer, so it is safer to leave them for a human to decide relevance. Do not flag this as a bug or suggest automatic removal of issue-derived labels in future reviews.


</details>

@krishnan05
Copy link
Copy Markdown
Contributor

Tip

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

🧩 Analysis chain
🏁 Script executed:

#!/bin/bash
# Check PR `#129` details and files changed
gh pr view 129 --repo AOSSIE-Org/SocialShareButton --json title,body,state,files

# Look for other PRs related to error handling
gh pr list --repo AOSSIE-Org/SocialShareButton --state all --search "error handling" --json number,title,state,mergedAt

# Check related issues
gh issue list --repo AOSSIE-Org/SocialShareButton --state all --search "error handling" --json number,title,state

Length of output: 5989

🏁 Script executed:

#!/bin/bash
# Check what PR `#99` changed (the already-merged error handling fix)
gh pr view 99 --repo AOSSIE-Org/SocialShareButton --json title,body,mergedAt

# Get the diff of PR `#129` to evaluate each try-catch
gh pr diff 129 --repo AOSSIE-Org/SocialShareButton

# Check current state of the main branch file
gh api repos/AOSSIE-Org/SocialShareButton/contents/src/social-share-button.js --jq '.content' | base64 -d | head -300

Length of output: 24433

@krishnan05 Great questions. Here's a detailed assessment:

1. Was this issue already resolved?

No — not by PR #99. PR #99 ("fix: avoid empty catch blocks in analytics", merged 2026-03-17) only addressed empty catch blocks inside the _emit() analytics method. PR #129 targets entirely different functions (createButton, share, copyLink, fallbackCopy), so there is no direct overlap or duplicate.

2. Was try-catch necessary at every instance?

Here's a breakdown of each addition:

Location Necessary? Reason
createButton()document.querySelector() ✅ Yes querySelector can throw a SyntaxError for invalid CSS selector strings — try-catch is appropriate here.
share()getShareURL() ⚠️ Marginal encodeURIComponent can theoretically throw a URIError for lone surrogates, but inputs come from window.location.href / document.title, which are extremely unlikely to contain invalid characters in practice.
share()window.location.href = shareUrl (email path) ❌ Unnecessary Assigning to window.location.href does not throw. Navigation restrictions produce silent no-ops or CSP errors — not exceptions catchable this way.
share()window.open() (other platforms) ❌ Unnecessary When blocked by a browser, window.open() returns null — it does not throw. A null-check (if (!window.open(...)) { ... }) would be the correct approach.
copyLink() → outer try-catch around navigator.clipboard.writeText() ❌ Unnecessary writeText() is async and returns a Promise — it never throws synchronously. The existing .catch() handler already covers async failures.
fallbackCopy() → rename _errerror + log ✅ Valid A reasonable improvement to the existing catch block.

3. Additional concern: bare console.error calls

All new catch blocks use bare console.error(...). Based on the established pattern for this repo (from previously merged PR #99 and the project's lint history), the approved approach is a debug-gated _debugWarn() helper, so that nothing is logged in production (options.debug === false). Bare console.error calls pollute end-user browser consoles and can expose internal details — this applies to all the catch blocks added in this PR.

Summary

The PR would benefit from being scoped down to only the genuinely useful additions (querySelector in createButton() and the fallbackCopy() improvement), removing the unnecessary try-catches around window.location.href, window.open(), and the synchronous wrapper around navigator.clipboard.writeText(), and replacing all bare console.error calls with the project's _debugWarn() pattern.

🧠 Learnings used

@coderabbitai
look at this conversation
#67 (comment)
fallbackCopy() → rename _err → error + log
mentioned by you as a change would undo/contradict that conversation. _err was introduced as per you comment back then

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 26, 2026

Tip

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

🧩 Analysis chain

Let me check that PR #67 discussion first.


🏁 Script executed:

#!/bin/bash
# Fetch the specific review comment from PR `#67`
gh api repos/AOSSIE-Org/SocialShareButton/pulls/comments/2913914202 --jq '{body: .body, path: .path, line: .line}'

echo "=== Context around the comment ==="
# Also fetch all review comments on PR `#67` to find context
gh api repos/AOSSIE-Org/SocialShareButton/pulls/67/comments --jq '.[] | select(.id == 2913914202 or (.body | contains("_err") or contains("fallbackCopy"))) | {id: .id, body: .body, path: .path, line: .line}'

Length of output: 7566


@krishnan05, you're absolutely right — I made an error in my earlier assessment. I apologize for the inconsistency.

Here's what the PR #67 discussion (at r2913914202) actually established for fallbackCopy():

  • ✅ Most preferred: catch {} — optional catch binding (ES2019+), since ecmaVersion: "latest" is set, and the error object is genuinely not needed
  • ✅ Also acceptable: catch (_err) — the _ prefix is explicitly supported by the caughtErrorsIgnorePattern: "^_" rule in eslint.config.js, communicating intentional non-use
  • ❌ Least preferred: catch (err) // eslint-disable-line no-unused-vars

PR #129's change of _errerror + console.error(...) logging directly contradicts that decision. The _err naming was a deliberate signal that the error is intentionally unused in fallbackCopy(). Renaming it to error and adding bare console.error is exactly the anti-pattern that the PR #67 discussion steered away from.

Corrected assessment for fallbackCopy(): ❌ This change should be reverted. The catch block should remain either:

} catch (_err) {
  copyBtn.textContent = "Failed";
}

or ideally (per the PR #67 recommendation):

} catch {
  copyBtn.textContent = "Failed";
}

This also means issue #132's acceptance criteria should have the fallbackCopy() item removed — that improvement is not needed (and would contradict the established convention). Only the createButton()document.querySelector() try-catch + _debugWarn logging item and the console.error_debugWarn replacement across other catch blocks remain valid.


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

Timestamp: 2026-03-26T08:58:58.716Z
Learning: In AOSSIE-Org/SocialShareButton (src/social-share-button.js), the `fallbackCopy()` catch block should use either optional catch binding `catch {}` (ES2019+, most preferred) or `catch (_err)` (also acceptable, suppressed by `caughtErrorsIgnorePattern: "^_"` in eslint.config.js). The error object is intentionally not used in this block. Do NOT rename `_err` to `error` or add any logging there — the established decision from PR `#67` (comment r2913914202) is that the catch variable must remain unused or omitted entirely.

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: 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-17T20:18:01.344Z
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: 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-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: 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.

Learnt from: SIDDHANTCOOKIE
Repo: AOSSIE-Org/SocialShareButton PR: 117
File: .github/workflows/sync-pr-labels.yml:159-172
Timestamp: 2026-03-20T20:22:01.941Z
Learning: In AOSSIE-Org/SocialShareButton PR `#117`, the overlapping file-based label mappings in `.github/workflows/sync-pr-labels.yml` (e.g., `.github/workflows/*.yml` triggering `configuration`, `github-actions`, and `ci-cd` simultaneously; `.jsx` triggering both `javascript` and `frontend`) are **intentional**. The design goal is comprehensive visibility — multiple labels are applied on purpose so maintainers can see all relevant categories a PR touches. Do not flag these overlaps as bugs or recommend exclusions/priority systems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants