diff --git a/src/index.ts b/src/index.ts index 00b3644..70e5e45 100644 --- a/src/index.ts +++ b/src/index.ts @@ -71,7 +71,11 @@ export class Socket { }); this.socket.on('error', (err) => { - this.closedReject(err); + if (err instanceof Error) { + this.closedReject(new SocketError(err.message)); + } else { + this.closedReject(new SocketError(err as string)); + } }); // types are wrong. fixed based on docs https://nodejs.org/dist/latest/docs/api/stream.html#streamduplextowebstreamduplex @@ -92,10 +96,10 @@ export class Socket { startTls(): Socket { if (this.secureTransport !== 'starttls') { - throw new Error("secureTransport must be set to 'starttls'"); + throw new SocketError("secureTransport must be set to 'starttls'"); } if (this.startTlsCalled) { - throw new Error('can only call startTls once'); + throw new SocketError('can only call startTls once'); } else { this.startTlsCalled = true; } @@ -104,4 +108,10 @@ export class Socket { } } +export class SocketError extends TypeError { + constructor(message: string) { + super(`SocketError: ${message}`); + } +} + export type * from './types'; diff --git a/test/index.test.ts b/test/index.test.ts index 3fbf492..5849ca0 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -1,7 +1,7 @@ import net from 'node:net'; import { once } from 'node:events'; import tap from 'tap'; -import { connect } from '../src'; +import { SocketError, connect } from '../src'; import { getReaderWriterFromSocket, listenAndGetSocketAddress, @@ -130,3 +130,16 @@ for (const data of [ }, ); } + +void tap.test('SocketError is thrown on connect failure', async (t) => { + t.plan(1); + + try { + const socket = connect('tcp://127.0.0.1:1234'); + await socket.closed; + } catch (err) { + t.same(err, new SocketError('connect ECONNREFUSED 127.0.0.1:1234')); + } finally { + t.end(); + } +}); diff --git a/test/tls.test.ts b/test/tls.test.ts index 1f3228c..f8a0872 100644 --- a/test/tls.test.ts +++ b/test/tls.test.ts @@ -2,7 +2,7 @@ import tls from 'node:tls'; import fs from 'node:fs'; import path from 'node:path'; import tap from 'tap'; -import { connect } from '../src'; +import { SocketError, connect } from '../src'; import { listenAndGetSocketAddress, writeAndReadSocket } from './utils'; function getTLSServer(): tls.Server { @@ -51,7 +51,7 @@ void tap.test('Socket `connect` with TLS', (t) => { () => { socket.startTls(); }, - new Error("secureTransport must be set to 'starttls'"), + new SocketError("secureTransport must be set to 'starttls'"), 'calling .startTls() throws an error', ); await socket.close(); @@ -98,7 +98,7 @@ void tap.test('Socket `connect` with TLS', (t) => { () => { socket.startTls(); }, - new Error('can only call startTls once'), + new SocketError('can only call startTls once'), 'second call to .startTls() throws an error', ); await socket.close();