TooTallNate/Java-WebSocket · error · IllegalArgumentException

Cannot send 'null' data to a WebSocketImpl.

Error message

Cannot send 'null' data to a WebSocketImpl.

What it means

send(String) throws IllegalArgumentException when the text argument is null. The library refuses to build frames from null payloads because a text message must have content; this is a fail-fast guard before draft.createFrames() would fail.

Solutions

  1. Null-check the payload before calling send().
  2. Send an empty string ("") explicitly if an empty message is intended.
  3. Catch IllegalArgumentException around send if null payloads are possible from upstream.
  4. Fix the upstream source so it never produces a null message.

Example fix

// before
ws.send(maybeNullText);
// after
if (maybeNullText != null) {
  ws.send(maybeNullText);
}
Defensive patterns

Strategy: validation

Validate before calling

if (text == null) { text = ""; } // or skip the send

Type guard

if (text instanceof String) { conn.send(text); }

Try / catch

try { conn.send(text); } catch (IllegalArgumentException e) { log.warn("null text payload dropped"); }

Prevention

When it happens

Trigger: Calling websocket.send((String) null), e.g. when the payload comes from a method that returned null or an uninitialized variable.

Common situations: Passing results of JSON lookups or database reads that can be null; generic send helpers that don't null-check their parameters; overloaded send(byte[]) vs send(String) confusion producing a null cast.

Related errors


AI-assisted analysis of TooTallNate/Java-WebSocket@afeacbf8c0 (2026-09-09). Data as JSON: /api/errors/52ffaa6661755e23. Report an issue: GitHub.

Appendix: source

Thrown at src/main/java/org/java_websocket/WebSocketImpl.java:643

  @Override
  public void close(int code) {
    close(code, "", false);
  }

  public void close(InvalidDataException e) {
    close(e.getCloseCode(), e.getMessage(), false);
  }

  /**
   * Send Text data to the other end.
   *
   * @throws WebsocketNotConnectedException websocket is not yet connected
   */
  @Override
  public void send(String text) {
    if (text == null) {
      throw new IllegalArgumentException("Cannot send 'null' data to a WebSocketImpl.");
    }
    send(draft.createFrames(text, role == Role.CLIENT));
  }

  /**
   * Send Binary data (plain bytes) to the other end.
   *
   * @throws IllegalArgumentException       the data is null
   * @throws WebsocketNotConnectedException websocket is not yet connected
   */
  @Override
  public void send(ByteBuffer bytes) {
    if (bytes == null) {
      throw new IllegalArgumentException("Cannot send 'null' data to a WebSocketImpl.");
    }
    send(draft.createFrames(bytes, role == Role.CLIENT));
  }

View on GitHub (pinned to afeacbf8c0)