Skip to content

fix(discord): catch thrown errors from gateway WebSocket close handler - #53854

Closed
joelnishanth wants to merge 2 commits into
openclaw:mainfrom
joelnishanth:fix/discord-websocket-crash-53644
Closed

joelnishanth wants to merge 2 commits into
openclaw:mainfrom
joelnishanth:fix/discord-websocket-crash-53644

Conversation

@joelnishanth

Copy link
Copy Markdown
Contributor

Summary

When the Discord WebSocket drops with code 1006 (abnormal closure), the internal @buape/carbon GatewayPlugin 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 emit method to catch errors thrown during the close event and converts them to emitted error events, allowing the existing error handling in provider.lifecycle.ts to process them gracefully.

Changes

  • Added wrapWebSocketWithErrorGuard() helper that intercepts the WebSocket's emit method and wraps close event handlers in try-catch
  • Modified SafeGatewayPlugin.createWebSocket() to apply the error guard to all WebSocket instances
  • Added comprehensive tests for the error wrapping behavior

Root 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

  • Added unit tests for wrapWebSocketWithErrorGuard
  • Verified existing provider.lifecycle.test.ts tests still pass
  • Verified all related gateway tests pass

Fixes #53644

— Joel Nishanth · offlyn.AI

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-apps

greptile-apps Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a process-crashing bug where Discord's WebSocket code 1006 (abnormal closure) would cause @buape/carbon's GatewayPlugin to throw synchronously inside a close-event callback — bypassing all Promise-based error handling and killing the gateway process. The fix wraps the WebSocket's emit method to catch any error thrown during close and re-routes it as an error event (via setImmediate) so the existing provider.lifecycle.ts error handling can deal with it gracefully.

  • The wrapWebSocketWithErrorGuard implementation is correct: originalEmit is captured before the patch, keeping re-entrancy safe; setImmediate defers the error emission to avoid calling emit from inside emit; and the listenerCount("error") > 0 guard (added in response to prior review feedback) prevents the fix from recreating the very crash it's trying to avoid if Carbon tears down its listeners before the next event-loop tick.
  • The known limitation (remaining close-listeners after the throwing one are silently skipped) is explicitly documented in the JSDoc, as requested in a prior review thread.
  • createWebSocket is refactored to a clean ternary and now applies the guard uniformly to both proxy and non-proxy sockets.
  • Test coverage is thorough: happy path, throw-to-error-event conversion, non-close pass-through, correct boolean return, and the no-listener swallow path are all exercised.

Confidence Score: 5/5

  • This PR is safe to merge — it fixes a real crash with a targeted, well-tested approach and all prior review concerns have been resolved.
  • The implementation is technically sound (correct emit-capture, setImmediate deferred re-emission, listenerCount guard), the known limitation is documented, tests are comprehensive covering all edge cases, and the two previously flagged issues (missing listenerCount check, missing JSDoc on partial-handler execution) have both been addressed in the final commit.
  • No files require special attention.

Reviews (2): Last reviewed commit: "fix(discord): guard against missing erro..." | Re-trigger Greptile

Comment on lines +243 to +245
setImmediate(() => {
originalEmit("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.

P1 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 49647e9. Added listenerCount check before emitting error to prevent uncaught exception if Carbon cleans up listeners before setImmediate fires.

Comment on lines +235 to +247
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;
}

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.

P1 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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
@joelnishanth

Copy link
Copy Markdown
Contributor Author

@greptile-apps please rescore

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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);

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.

P2 Badge 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 👍 / 👎.

@steipete

Copy link
Copy Markdown
Contributor

Closing as superseded by #54182, merged on March 25, 2026. Same Discord 1006 crash symptom, and #54182 landed the maintainable fix in the lifecycle teardown path.

@steipete steipete closed this Mar 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: discord Channel integration: discord size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Discord WebSocket code 1006 triggers uncaught exception and crashes gateway instead of reconnecting

2 participants