{"record":{"id":"a294ba84beae405a","repo":"grafana/k6","slug":"invalidstateerror","errorCode":null,"errorMessage":"InvalidStateError","messagePattern":"InvalidStateError","errorType":"exception","errorClass":"InvalidStateError","httpStatus":null,"severity":"error","filePath":"internal/js/modules/k6/websockets/websockets.go","lineNumber":860,"sourceCode":"\t\tTimeSeries: metrics.TimeSeries{\n\t\t\tMetric: w.builtinMetrics.WSPing,\n\t\t\tTags:   w.tagsAndMeta.Tags,\n\t\t},\n\t\tTime:     pongTimestamp,\n\t\tMetadata: w.tagsAndMeta.Metadata,\n\t\tValue:    metrics.D(pongTimestamp.Sub(pingTimestamp)),\n\t})\n}\n\n// assertStateOpen checks if the websocket is in the OPEN state\n// otherwise it throws an error (panic)\nfunc (w *webSocket) assertStateOpen() {\n\tif w.readyState == OPEN {\n\t\treturn\n\t}\n\n\t// TODO figure out if we should give different error while being closed/closed/connecting\n\tcommon.Throw(w.vu.Runtime(), errors.New(\"InvalidStateError\"))\n}\n\nfunc isValidClientCloseCode(code int) bool {\n\treturn code == 1000 || (code >= 3000 && code <= 4999)\n}\n\nfunc isValidCloseReason(reason string) bool {\n\treturn len([]byte(reason)) <= 123\n}\n\nfunc (w *webSocket) close(code int, reason string) error {\n\tif code != 0 && !isValidClientCloseCode(code) {\n\t\treturn fmt.Errorf(\n\t\t\t\"InvalidAccessError: Failed to execute 'close' on 'WebSocket': \"+\n\t\t\t\t\"The close code must be either 1000, or between 3000 and 4999. %d is neither\",\n\t\t\tcode,\n\t\t)\n\t}","sourceCodeStart":842,"sourceCodeEnd":878,"githubUrl":"https://github.com/grafana/k6/blob/3fcf5388d78cb382f0c0d42ec556a06bfd1b8dee/internal/js/modules/k6/websockets/websockets.go#L842-L878","documentation":"Thrown by send() and ping() on k6/experimental/websockets sockets when the connection is not in the OPEN state. assertStateOpen (internal/js/modules/k6/websockets/websockets.go:750) panics with a bare InvalidStateError whenever readyState is CONNECTING, CLOSING, or CLOSED, mirroring the browser API where sending or pinging a not-yet-open or already-closed socket is invalid.","triggerScenarios":"Calling ws.send(...) or ws.ping() immediately after new WebSocket(url) — the constructor starts the connection in a background goroutine, so the socket is still CONNECTING; or calling them after close(), after a server-initiated close, or from a timer that outlived the connection.","commonSituations":"Migrating scripts from the legacy k6/ws module, where the setup callback only runs once the socket is open; sending from setTimeout/setInterval without checking state; VU iterations that reuse a closed socket handle.","solutions":["Move sends into the open handler: ws.addEventListener('open', () => ws.send('hello'))","Guard every send/ping call site: if (ws.readyState === WebSocket.OPEN) ws.send(...)","Remember ping() follows the same rule — only ping an OPEN socket"],"exampleFix":"// before\nconst ws = new WebSocket('wss://example.com');\nws.send('hello'); // still CONNECTING → InvalidStateError\n\n// after\nconst ws = new WebSocket('wss://example.com');\nws.addEventListener('open', () => ws.send('hello'));","handlingStrategy":"type-guard","validationCode":"function sendWhenOpen(ws, data) {\n  if (ws.readyState !== WebSocket.OPEN) {\n    // drop or buffer; never call send()/ping() while CONNECTING/CLOSING/CLOSED\n    return false;\n  }\n  ws.send(data);\n  return true;\n}","typeGuard":"function isOpen(ws) {\n  return ws.readyState === WebSocket.OPEN; // 1\n}","tryCatchPattern":"try {\n  ws.send(payload);\n} catch (err) {\n  if (String(err.message) !== 'InvalidStateError') throw err;\n  console.warn('socket not OPEN — requeue the payload in the open handler');\n}","preventionTips":["Send only from the 'open' event handler (or after readyState reaches OPEN)","Guard timed sends (setInterval/setInterval-like setup functions) with an isOpen check","Track the socket lifecycle in setup/teardown so VU iterations never reuse a closed handle"],"tags":["websocket","invalid-state","ready-state","send","ping"],"backgroundTag":"websocket-not-open","analyzedSha":"3fcf5388d78cb382f0c0d42ec556a06bfd1b8dee","analyzedAt":"2026-08-18T03:05:52.393Z","contentChangedAt":"2026-08-18T03:05:52.393Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}