Skip to content

fix: add try-catch for querySelector and log fallbackCopy errors (#132) - #199

Open
afzalansari12 wants to merge 2 commits into
AOSSIE-Org:mainfrom
afzalansari12:fix/132-try-catch-error-handling
Open

fix: add try-catch for querySelector and log fallbackCopy errors (#132)#199
afzalansari12 wants to merge 2 commits into
AOSSIE-Org:mainfrom
afzalansari12:fix/132-try-catch-error-handling

Conversation

@afzalansari12

@afzalansari12 afzalansari12 commented Jul 25, 2026

Copy link
Copy Markdown

Addressed Issues:

Fixes #132

Screenshots/Recordings:

Not applicable — this is an internal error-handling improvement with no visual/UI change.

Additional Notes:

  • Wrapped document.querySelector(raw) in _resolveContainer() with a try-catch, since querySelector throws a SyntaxError on an invalid CSS selector, and the selector is user-supplied via options.container.
  • Updated the fallbackCopy() catch block to bind the error variable (_errerror) and log it via this._debugWarn() instead of silently swallowing it.
  • Verified npm run lint passes with no errors and the script still parses correctly (node --check).
  • Manually tested both error paths locally:
    • Instantiating with an invalid container selector (###invalid[[[) now logs a warning via console instead of throwing an uncaught SyntaxError.
    • Forcing document.execCommand to throw inside fallbackCopy() now logs [SocialShareButton Analytics] fallbackCopy failed <error> via _debugWarn (with debug: true), and the copy button correctly updates to "Failed".

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 handling of clipboard-copy fallback failures by capturing the underlying error and emitting debug warnings before showing the existing “Failed” state.
    • Invalid container selector input is now handled gracefully: selector lookup is wrapped in safe logic, triggers a warning (when debug is enabled), and fails without disrupting the page.
    • Debug logging output has been standardized with a clearer component prefix.

@github-actions github-actions Bot added javascript JavaScript/TypeScript code changes size/S Small PR (11-50 lines changed) first-time-contributor First PR of an external contributor needs-review labels Jul 25, 2026
@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 9d2b64ba-a509-4154-8404-cbce9538e728

📥 Commits

Reviewing files that changed from the base of the PR and between f67a5a6 and 0782a4c.

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

Walkthrough

SocialShareButton now passes debug settings into container resolution, safely handles invalid selectors, and logs clipboard fallback errors before preserving failure behavior.

Changes

SocialShareButton error handling

Layer / File(s) Summary
Container selector validation
src/social-share-button.js
Container resolution receives the debug option, catches invalid selector errors, warns with a general prefix, and returns null.
Clipboard fallback diagnostics
src/social-share-button.js
fallbackCopy logs caught errors with _debugWarn before preserving the existing failed UI state.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested labels: Typescript Lang

Suggested reviewers: kpj2006

Poem

I’m a rabbit with logs in my burrow tonight,
Catching bad selectors before they take flight.
Clipboard woes get a debugful cheer,
And failed states stay nicely clear.
Hop, hop—errors now appear!

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding try-catch handling for querySelector and logging fallbackCopy errors.
Linked Issues check ✅ Passed The PR implements both requested error-handling updates for querySelector and fallbackCopy logging in #132.
Out of Scope Changes check ✅ Passed The changes stay focused on defensive error handling and related logging, with no clear unrelated additions.
✨ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/social-share-button.js`:
- Around line 536-537: Update the catch block in the clipboard fallback flow to
use a domain-neutral debug warning instead of the analytics-specific _debugWarn
labeling, and add a concise inline comment explaining this debug-only failure
path. Generalize _debugWarn or introduce a suitable neutral helper while
preserving the existing error details.
- Around line 736-748: Update static _resolveContainer to route invalid-selector
diagnostics through the shared _debugWarn helper instead of calling console.warn
directly. Make the helper usable from this pre-instance path, passing the
relevant debug setting such as options.debug or using a module-level helper,
while keeping the no-console suppression centralized in that helper.
🪄 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 Plus

Run ID: 4bfe145e-42c6-48ba-8a2d-f759661c510c

📥 Commits

Reviewing files that changed from the base of the PR and between 5673fea and f67a5a6.

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

Comment thread src/social-share-button.js
Comment on lines +736 to +748

static _resolveContainer(raw) {
if (!raw) return null;
if (typeof document === "undefined") return null;
return typeof raw === "string" ? document.querySelector(raw) : raw;
if (typeof raw !== "string") return raw;

try {
return document.querySelector(raw);
} catch (error) {
// eslint-disable-next-line no-console
console.warn("[SocialShareButton] Invalid container selector:", raw, error);
return null;
}

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Route selector diagnostics through the shared warning helper.

Lines 745-746 introduce another inline console.warn and bypass _debugWarn(), causing invalid selectors to log regardless of the library’s debug setting. Make the helper callable from this static, pre-instance path—such as by passing options.debug into the resolver or using a module-level helper—and keep the no-console suppression in one place.

Based on learnings, debugging logs in src/social-share-button.js should be consolidated through a private _debugWarn helper instead of adding per-line inline console.* calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/social-share-button.js` around lines 736 - 748, Update static
_resolveContainer to route invalid-selector diagnostics through the shared
_debugWarn helper instead of calling console.warn directly. Make the helper
usable from this pre-instance path, passing the relevant debug setting such as
options.debug or using a module-level helper, while keeping the no-console
suppression centralized in that helper.

Source: Learnings

@afzalansari12

Copy link
Copy Markdown
Author

Thanks for the suggestion! Since _resolveContainer() is a static method and _debugWarn() is instance-based, would you prefer converting _debugWarn() into a shared/static helper, or is guarding console.warn() behind the debug option acceptable here

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

Labels

first-time-contributor First PR of an external contributor javascript JavaScript/TypeScript code changes needs-review size/S Small PR (11-50 lines changed)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improvement: Add try-catch blocks for better error handling in social-share-button.js

1 participant