Repository navigation
fix(discord): catch thrown errors from gateway WebSocket close handler - #53854
joelnishanth wants to merge 2 commits into
Conversation
Wrap WebSocket emit to catch errors thrown by Carbon's GatewayPlugin during close event handling (e.g., "Max reconnect attempts reached") and convert them to emitted error events that existing lifecycle error handling can process gracefully. Fixes openclaw#53644
Greptile SummaryThis PR fixes a process-crashing bug where Discord's WebSocket code
Confidence Score: 5/5
Reviews (2): Last reviewed commit: "fix(discord): guard against missing erro..." | Re-trigger Greptile |
| setImmediate(() => { | ||
| originalEmit("error", error); | ||
| }); |
There was a problem hiding this comment.
Potential unhandled error if no
error listener is registered
When setImmediate fires and calls originalEmit("error", error), Node.js's EventEmitter contract is: if the "error" event is emitted and there are no registered "error" listeners, Node.js throws the error as an uncaught exception (process crash). This can happen if Carbon cleans up its WebSocket event listeners synchronously during — or immediately after — the close-event dispatch, before the setImmediate callback runs.
The close-event handler threw (interrupting Carbon's own cleanup), but Carbon may still have other code paths or the WebSocket's finalization logic that removes listeners synchronously before the next event-loop phase. If that happens, originalEmit("error", error) will throw an uncaught exception, recreating the exact crash this PR is trying to prevent.
A minimal defensive guard would be to check for listeners before emitting:
setImmediate(() => {
if (emitter.listenerCount("error") > 0) {
originalEmit("error", error);
} else {
// Fallback: log the swallowed error so it isn't silently lost
logVerbose(`discord gateway: no error listeners, swallowing close error: ${String(error)}`);
}
});This ensures the setImmediate callback is always safe, regardless of listener state at call time.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/discord/src/monitor/gateway-plugin.ts
Line: 243-245
Comment:
**Potential unhandled error if no `error` listener is registered**
When `setImmediate` fires and calls `originalEmit("error", error)`, Node.js's `EventEmitter` contract is: if the `"error"` event is emitted and there are no registered `"error"` listeners, Node.js **throws the error as an uncaught exception** (process crash). This can happen if Carbon cleans up its WebSocket event listeners synchronously during — or immediately after — the close-event dispatch, before the `setImmediate` callback runs.
The close-event handler threw (interrupting Carbon's own cleanup), but Carbon may still have other code paths or the WebSocket's finalization logic that removes listeners synchronously before the next event-loop phase. If that happens, `originalEmit("error", error)` will throw an uncaught exception, recreating the exact crash this PR is trying to prevent.
A minimal defensive guard would be to check for listeners before emitting:
```ts
setImmediate(() => {
if (emitter.listenerCount("error") > 0) {
originalEmit("error", error);
} else {
// Fallback: log the swallowed error so it isn't silently lost
logVerbose(`discord gateway: no error listeners, swallowing close error: ${String(error)}`);
}
});
```
This ensures the `setImmediate` callback is always safe, regardless of listener state at call time.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Fixed in 49647e9. Added listenerCount check before emitting error to prevent uncaught exception if Carbon cleans up listeners before setImmediate fires.
| if (eventName === "close") { | ||
| try { | ||
| return originalEmit(eventName, ...args); | ||
| } catch (error) { | ||
| logVerbose(`discord gateway: caught thrown error during WebSocket close: ${String(error)}`); | ||
| // Convert the thrown error to an emitted 'error' event so existing | ||
| // error handling in provider.lifecycle.ts can process it gracefully. | ||
| // Use setImmediate to avoid re-entrancy issues with emit. | ||
| setImmediate(() => { | ||
| originalEmit("error", error); | ||
| }); | ||
| return true; | ||
| } |
There was a problem hiding this comment.
Partial close-handler execution on throw
originalEmit(eventName, ...args) iterates through all registered "close" listeners and stops as soon as one throws. Once the guard catches the exception and returns true, the remaining close listeners that were registered after the throwing one are silently skipped.
If Carbon (or any other component) registers a second "close" listener for cleanup (e.g. to reset internal state or tear down timers), that listener will never run, potentially leaving Carbon in an inconsistent/zombie state (active timers, stale session state, etc.).
This is unlikely to be an issue with the current version of @buape/carbon, but is worth an explicit comment documenting the known limitation, and a note to revisit if Carbon's close handler count changes.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/discord/src/monitor/gateway-plugin.ts
Line: 235-247
Comment:
**Partial close-handler execution on throw**
`originalEmit(eventName, ...args)` iterates through all registered `"close"` listeners and stops as soon as one throws. Once the guard catches the exception and returns `true`, the remaining close listeners that were registered after the throwing one are silently skipped.
If Carbon (or any other component) registers a second `"close"` listener for cleanup (e.g. to reset internal state or tear down timers), that listener will never run, potentially leaving Carbon in an inconsistent/zombie state (active timers, stale session state, etc.).
This is unlikely to be an issue with the current version of `@buape/carbon`, but is worth an explicit comment documenting the known limitation, and a note to revisit if Carbon's close handler count changes.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Fixed in 49647e9. Added JSDoc comment documenting the known limitation about partial close-handler execution if a handler throws.
…e handler Address Greptile review feedback: - Check listenerCount before emitting error to prevent uncaught exception if Carbon cleans up listeners before setImmediate fires - Document known limitation about partial close-handler execution
|
@greptile-apps please rescore |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 49647e9088
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| */ | ||
| function wrapWebSocketWithErrorGuard(ws: WebSocket): WebSocket { | ||
| const emitter = ws as EventEmitter; | ||
| const originalEmit = emitter.emit.bind(emitter); |
There was a problem hiding this comment.
Guard non-EventEmitter sockets before overriding emit
wrapWebSocketWithErrorGuard now unconditionally does emitter.emit.bind(emitter), which throws immediately when the WebSocket object is not EventEmitter-compatible. This regresses the existing proxy path test setup (extensions/discord/src/monitor/provider.proxy.test.ts mocks ws with a constructor-only class), and the same crash would occur at runtime with any EventTarget-style socket implementation. Add a runtime capability check (for emit/listenerCount) and skip wrapping when those methods are absent.
Useful? React with 👍 / 👎.
Summary
When the Discord WebSocket drops with code 1006 (abnormal closure), the internal
@buape/carbonGatewayPlugin throws an exception (Max reconnect attempts (0) reached after code 1006) instead of emitting it as an error event. This thrown exception bypasses OpenClaw's lifecycle error handling and crashes the entire gateway process.This PR wraps the WebSocket's
emitmethod to catch errors thrown during thecloseevent and converts them to emittederrorevents, allowing the existing error handling inprovider.lifecycle.tsto process them gracefully.Changes
wrapWebSocketWithErrorGuard()helper that intercepts the WebSocket'semitmethod and wraps close event handlers in try-catchSafeGatewayPlugin.createWebSocket()to apply the error guard to all WebSocket instancesRoot Cause
The Carbon library's
GatewayPlugin.handleReconnectionAttempt()throws an error when reconnect attempts are exhausted. This error originates in a WebSocket event callback, so it escapes the normal Promise/async error handling and becomes an uncaught exception that Node.js cannot catch without a process-level handler.Test Plan
wrapWebSocketWithErrorGuardprovider.lifecycle.test.tstests still passFixes #53644
— Joel Nishanth · offlyn.AI