Skip to content

Incorrect error event when calling stream.destroy(err) #2310

@SystemParadox

Description

@SystemParadox

Is there an existing issue for this?

  • I've searched for any related issues and avoided creating a duplicate issue.

Description

I am trying to fix mqttjs/MQTT.js#1939, but createWebSocketStream seems to swallow errors passed to stream.destroy().

Consider the following example:

import WebSocket, { createWebSocketStream } from 'ws';

const ws = new WebSocket('wss://localhost:1234');
const stream = createWebSocketStream(ws, { encoding: 'utf8' });

stream.on('error', console.error);

stream.destroy(new Error('die'));

ws version

8.17.1 and 8.19.0

Node.js Version

20.19.5

System

OS: Linux 6.8 Linux Mint 22.1 (Xia)
CPU: (12) x64 AMD Ryzen 5 2600 Six-Core Processor
Memory: 32.61 GB / 46.96 GB
Container: Yes
Shell: 5.2.21 - /bin/bash

Expected result

According to the NodeJS documentation for writable.destroy(), calling stream.destroy(err) should emit an error event with err:

const { Writable } = require('node:stream');

const myStream = new Writable();

const fooErr = new Error('foo error');
myStream.destroy(fooErr);
myStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error 

Which is exactly what happens:

foo error

Actual result

The createWebSocketStream example above throws a completely different error instead of the one I expected:

Error: WebSocket was closed before the connection was established
    at WebSocket.terminate (/home/simon/github/MQTT.js/node_modules/ws/lib/websocket.js:490:7)
    at duplex._destroy (/home/simon/github/MQTT.js/node_modules/ws/lib/stream.js:110:32)
    at _destroy (node:internal/streams/destroy:121:10)
    at Duplex.destroy (node:internal/streams/destroy:83:5)
    at Writable.destroy (node:internal/streams/writable:1122:11)
    at file:///home/simon/github/MQTT.js/test.js:8:8
    at ModuleJob.run (node:internal/modules/esm/module_job:325:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:606:24)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)

This is not expected behaviour - stream.destroy(err) should emit an error event with err.

Attachments

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions