Improvement: added error handling using try-catch#129
Improvement: added error handling using try-catch#129Akshat0125 wants to merge 1 commit intoAOSSIE-Org:mainfrom
Conversation
WalkthroughError 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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 | 🟠 MajorAbort 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()andattachEvents()still run. The React/Preact wrappers instantiate this constructor directly, so this becomes a silent initialization failure instead of a surfaced one. HavecreateButton()signal failure soinit()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
📒 Files selected for processing (1)
src/social-share-button.js
| } catch (error) { | ||
| console.error("DOM manipulation failed: Invalid container selector", error); |
There was a problem hiding this comment.
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.
| 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); | ||
| } |
There was a problem hiding this comment.
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.
|
@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 |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 5283 🏁 Script executed: Length of output: 6318
1. Was the issue already resolved?Not fully. Before this PR, only 2. Are all try-catch blocks necessary?
The two most problematic additions are the 3. Critical pattern violationAll new catch blocks use bare // ✅ 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 Summary recommendationThis PR should be requested to change on the following grounds:
🧠 Learnings used |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 5989 🏁 Script executed: Length of output: 24433
1. Was this issue already resolved?No — not by PR 2. Was try-catch necessary at every instance?Here's a breakdown of each addition:
3. Additional concern: bare
|
@coderabbitai Please mark any redundant or unnecessary try-catch blocks directly in the review comments so the contributor can identify and address them. |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chainSure, 🏁 Script executed: 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: Length of output: 271 The review endpoint returned 403. Let me try posting individual inline diff comments directly. 🏁 Script executed: Length of output: 880
❌ Line 425 —
|
|
@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. |
@Akshat0125. Also link the issue created by coderabbit in this PR and read contributing.md. Join discord sever and give updates there |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chainSure, 🏁 Script executed: Length of output: 45 The assignee lookup failed. Retrying without the 🏁 Script executed: Length of output: 58
It covers:
🧠 Learnings used |
|
@coderabbitai Remove not necessary part in the issue #132 |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chainSure, 🏁 Script executed: 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: Length of output: 163
Updated issue body (copy-paste into ## 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 Acceptance Criteria
Learnt from: kpj2006 Learnt from: kpj2006 Learnt from: krishnan05 Learnt from: kpj2006 Learnt from: kpj2006 Learnt from: kpj2006 Learnt from: SIDDHANTCOOKIE Learnt from: SIDDHANTCOOKIE |
@coderabbitai |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chainLet me check that PR 🏁 Script executed: Length of output: 7566
Here's what the PR
PR Corrected assessment for } catch (_err) {
copyBtn.textContent = "Failed";
}or ideally (per the PR } catch {
copyBtn.textContent = "Failed";
}This also means issue ✏️ Learnings added
🧠 Learnings used |
Addressed Issues:
Fixes #(issue number)
Screenshots/Recordings:
Additional Notes:
Checklist
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