{"id":"21fd53d0970da278","repo":"websockets/ws","slug":"first-argument-must-be-a-valid-error-code-number","errorCode":null,"errorMessage":"First argument must be a valid error code number","messagePattern":"First argument must be a valid error code number","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"lib/sender.js","lineNumber":190,"sourceCode":"    return [target, data];\n  }\n\n  /**\n   * Sends a close message to the other peer.\n   *\n   * @param {Number} [code] The status code component of the body\n   * @param {(String|Buffer)} [data] The message component of the body\n   * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n   * @param {Function} [cb] Callback\n   * @public\n   */\n  close(code, data, mask, cb) {\n    let buf;\n\n    if (code === undefined) {\n      buf = EMPTY_BUFFER;\n    } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n      throw new TypeError('First argument must be a valid error code number');\n    } else if (data === undefined || !data.length) {\n      buf = Buffer.allocUnsafe(2);\n      buf.writeUInt16BE(code, 0);\n    } else {\n      const length = Buffer.byteLength(data);\n\n      if (length > 123) {\n        throw new RangeError('The message must not be greater than 123 bytes');\n      }\n\n      buf = Buffer.allocUnsafe(2 + length);\n      buf.writeUInt16BE(code, 0);\n\n      if (typeof data === 'string') {\n        buf.write(data, 2);\n      } else if (isUint8Array(data)) {\n        buf.set(data, 2);\n      } else {","sourceCodeStart":172,"sourceCodeEnd":208,"githubUrl":"https://github.com/websockets/ws/blob/ae1de54330cef77e487548890fabfeb9aae1d83d/lib/sender.js#L172-L208","documentation":"Thrown as a TypeError by Sender.close() (sender.js:189-190) when the code argument is provided but is either not a number or fails isValidStatusCode(). Valid status codes per WebSocket close-frame rules (RFC 6455 §7.4) are: 1000-1014 (excluding 1004, 1005, 1006), and 3000-4999. Any other value — such as 0, 200, 1005, 9999, a string, or null — causes this synchronous throw that propagates to the caller of ws.close().","triggerScenarios":"Calling ws.close(code) or ws.close(code, reason) where code is a non-number (e.g. a string '1000', undefined paired with a reason, null) or a number outside the valid ranges. Internally, WebSocket.close() at websocket.js:322 passes code directly to sender.close(), so the throw surfaces synchronously from the ws.close() call site.","commonSituations":"A developer passes a custom error code like 200 or 6000 which is outside the allowed ranges. Someone passes code as a string instead of a number. A developer uses 1005/1006 (reserved/forbidden codes) thinking they are sendable. Passing null or 0 as a code. Confusing application-level error codes with WebSocket close codes.","solutions":["Use a valid WebSocket close code: 1000-1014 (except 1004/1005/1006) or 3000-4999.","Ensure the code argument is a number, not a string — convert with Number() or parseInt() before calling close().","Omit the code argument entirely (call ws.close() with no arguments) to send a close frame with no status code.","If you need application-specific codes, use the 3000-4999 range."],"exampleFix":"// before — invalid code (reserved)\nws.close(1005, 'going away');\n\n// after — use a valid sendable code\nws.close(1001, 'going away');","handlingStrategy":"validation","validationCode":"const { isValidStatusCode } = require('ws/lib/validation');\n\nfunction closeSafely(ws, code, reason) {\n  if (code === undefined || code === null) {\n    ws.close();\n    return;\n  }\n  if (typeof code !== 'number' || !isValidStatusCode(code)) {\n    throw new TypeError(`Invalid close code: ${code}`);\n  }\n  ws.close(code, reason);\n}","typeGuard":"function isValidCloseCode(code) {\n  return (\n    typeof code === 'number' &&\n    ((code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006) ||\n      (code >= 3000 && code <= 4999))\n  );\n}","tryCatchPattern":"try {\n  ws.close(code, reason);\n} catch (err) {\n  if (err instanceof TypeError && err.message.includes('valid error code')) {\n    // Fall back to a generic normal closure\n    console.warn(`Invalid close code ${code}; closing with 1000 instead.`);\n    ws.close(1000, reason);\n  } else {\n    throw err;\n  }\n}","preventionTips":["Always validate the close code against the allowed ranges (1000-1014 except 1004/1005/1006, or 3000-4999) before calling ws.close().","Ensure code is a number, not a string — convert with Number() if it comes from user input.","Omit the code argument entirely when you want a close frame with no status body.","Use the 3000-4999 range for application-specific close codes.","Never use 1005 or 1006 — those are reserved for internal use and cannot appear in a close frame."],"tags":["websocket","close-frame","status-code","sender","validation"],"analyzedSha":"ae1de54330cef77e487548890fabfeb9aae1d83d","analyzedAt":"2026-08-03T19:11:18.437Z","schemaVersion":2}