Skip to content

Handle WebSocket Closing Error#16

Merged
dank merged 2 commits into
dank:masterfrom
LEX0RE:patch-1
Jun 24, 2026
Merged

Handle WebSocket Closing Error#16
dank merged 2 commits into
dank:masterfrom
LEX0RE:patch-1

Conversation

@LEX0RE

@LEX0RE LEX0RE commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Fix false ERROR log on intentional WebSocket close

Problem

When Close() is called explicitly on a PsyNetRPC instance, the internal readMessages() goroutine is blocked on wsConn.ReadMessage(). Closing the underlying TCP socket causes ReadMessage() to return a use of closed network connection error, which is then logged as ERROR:

{"level":"ERROR","msg":"failed to read websocket message","err":"read tcp 172.22.0.8:38354->34.149.116.40:443: use of closed network connection"}

This is misleading — the connection was closed intentionally, not due to a real network failure. A common pattern that triggers this is opening a short-lived RPC connection per request:

rpc, _, err := GetRPC(psyNet, player)
if err != nil {
    return err
}
defer rpc.Close() // closes the socket → readMessages logs a false ERROR

profiles, err := rpc.GetProfiles(ctx, playerIDs)

Root cause

readMessages() does not distinguish between an expected closure (triggered by Close()) and an unexpected network error. Both are logged at ERROR level.

Fix

Check the connected flag — which is already set to false by Close() before the socket is closed — to determine whether the error is expected:

if err != nil {
    p.mu.Lock()
    expected := !p.connected
    p.mu.Unlock()

    if expected {
        p.logger.Debug("websocket closed normally", slog.Any("err", err))
    } else {
        p.logger.Error("failed to read websocket message", slog.Any("err", err))
    }
    break
}

This way, intentional closures are logged at DEBUG level, while real unexpected errors remain at ERROR.

Why not websocket.IsUnexpectedCloseError?

use of closed network connection is a raw TCP-level error, not a WebSocket close frame. IsUnexpectedCloseError only handles proper WebSocket close codes and would not catch this case.

@LEX0RE LEX0RE changed the title Handle the case Handle WebSocket Closing Error Jun 24, 2026
Comment thread psynetrpc.go Outdated
LEX0RE and others added 2 commits June 24, 2026 18:25
Handle websocket read errors with connection state check.
@dank dank merged commit 5db30b3 into dank:master Jun 24, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants