Skip to content

Commit ef0089f

Browse files
authored
fix(client, server, shared): throw distinct errors for timeouts and closed connections (#2533)
## What - Timeout plugins (`TimeoutLinkPlugin`, `TimeoutHandlerPlugin`) now abort with a `TimeoutError`, named like the error of `AbortSignal.timeout()`. Exported from `@orpc/client` and `@orpc/server`. - WebSocket and MessagePort links now reject with a `ConnectionClosedError` (exported from `@orpc/client`) when the connection is closed, lost, or cannot be reopened. - User cancellation stays `AbortError`. ## Why Both cases were thrown as `AbortError`, so they looked like the user calling `signal.abort()`. Tracing recorded them at `info` instead of failing the span, pino/evlog treated them as benign aborts, and users could only tell them apart by message string. `isAbortError`, `recordSpanError`, the loggers and the retry plugin need no logic change: the new names do not contain `Abort`, so they are now treated as failures, and `isRetryableError` already retries errors without a response. ## Breaking - Timeouts reject / set `signal.reason` to `TimeoutError` instead of `AbortError`. - WebSocket and MessagePort links reject with `ConnectionClosedError` instead of `AbortError`. Messages are unchanged. ## Notes for review - Server peer adapters still abort the request signal with `AbortError` when the client goes away, same as an HTTP client disconnecting. - The fetch link is untouched: a dropped HTTP connection already rejects with the platform `TypeError`, which is not an abort. - A handler that rethrows the `TimeoutError` still responds with a generic 500. - In the websocket transport only the error class and its import changed. - Docs: the timeout plugin page now says `TimeoutError`; no new sections. ## Testing `pnpm check` and `pnpm docs:validate` pass. `pnpm vitest run` passes except `packages/openapi-inference/src/openapi-generator.test.ts` ("names the nearest tsconfig…"), which fails locally on a `/private/var` vs `/var` temp-path mismatch and is unrelated. `packages/bun` tests were not run locally (no `bun`).
1 parent 624e8c2 commit ef0089f

17 files changed

Lines changed: 159 additions & 51 deletions

File tree

‎apps/content/docs/plugins/timeout.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ sidebar:
77

88
## Client
99

10-
Use `TimeoutLinkPlugin` to abort requests that exceed the timeout with an `AbortError`:
10+
Use `TimeoutLinkPlugin` to abort requests that exceed the timeout with a `TimeoutError`:
1111

1212
```ts
1313
import { TimeoutLinkPlugin } from '@orpc/client/plugins'
@@ -27,7 +27,7 @@ The `link` can be any supported oRPC link, such as [RPCLink](/docs/rpc/link), [O
2727

2828
## Server
2929

30-
Use `TimeoutHandlerPlugin` to abort the request signal with an `AbortError` when handling exceeds the timeout:
30+
Use `TimeoutHandlerPlugin` to abort the request signal with a `TimeoutError` when handling exceeds the timeout:
3131

3232
```ts handler
3333
import { TimeoutHandlerPlugin } from '@orpc/server/plugins'

‎packages/client/src/adapters/message-port/rpc-link.test.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { AbortError, sleep } from '@orpc/shared'
1+
import { sleep } from '@orpc/shared'
22
import { decodePeerMessage, encodePeerMessage } from '@standard-server/peer'
33

44
import { createORPCClient } from '../../client'
5+
import { ConnectionClosedError } from '../../error'
56
import { RPCLink } from './rpc-link'
67

78
describe('rpcLink', () => {
@@ -83,7 +84,9 @@ describe('rpcLink', () => {
8384
const port = createPort()
8485
const orpc = createORPCClient(new RPCLink({ port })) as any
8586

86-
const promise = expect(orpc.ping('input')).rejects.toThrow(new AbortError('MessagePort closed'))
87+
const promise = expect(orpc.ping('input')).rejects.toThrow(
88+
new ConnectionClosedError('MessagePort closed'),
89+
)
8790

8891
await sleep(0)
8992

@@ -98,7 +101,10 @@ describe('rpcLink', () => {
98101

99102
onClose()
100103

101-
await expect(orpc.ping('input')).rejects.toThrow(new AbortError('MessagePort closed'))
104+
await expect(orpc.ping('input')).rejects.toThrow(
105+
new ConnectionClosedError('MessagePort closed'),
106+
)
107+
await expect(orpc.ping('input')).rejects.toBeInstanceOf(ConnectionClosedError)
102108
expect(port.postMessage).not.toHaveBeenCalled()
103109
})
104110

‎packages/client/src/adapters/message-port/transport.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { Promisable, Value } from '@orpc/shared'
2-
import { AbortError, value } from '@orpc/shared'
2+
import { value } from '@orpc/shared'
33
import type { StandardLazyResponse, StandardRequest } from '@standard-server/core'
44
import type {
55
DecodePeerMessageOptions,
@@ -14,6 +14,7 @@ import {
1414
isServerPeerSendMessage,
1515
} from '@standard-server/peer'
1616

17+
import { ConnectionClosedError } from '../../error'
1718
import type { ClientContext, ClientOptions } from '../../types'
1819
import type { StandardLinkTransport } from '../standard/index'
1920
import type { SupportedMessagePort } from './message-port'
@@ -64,7 +65,7 @@ export class MessagePortLinkTransport<T extends ClientContext> implements Standa
6465
encodePeerMessage: encodePeerMessageOptions,
6566
decodePeerMessage: decodePeerMessageOptions,
6667
}: MessagePortLinkTransportOptions<T>) {
67-
let closeReason: undefined | AbortError
68+
let closeReason: undefined | ConnectionClosedError
6869

6970
this.peer = new ClientPeer(async (message) => {
7071
// `postMessage` silently discards data once the port is closed, so requests would never settle
@@ -110,7 +111,7 @@ export class MessagePortLinkTransport<T extends ClientContext> implements Standa
110111
})
111112

112113
onMessagePortClose(port, async () => {
113-
closeReason = new AbortError('MessagePort closed')
114+
closeReason = new ConnectionClosedError('MessagePort closed')
114115
await this.peer.close(closeReason)
115116
})
116117
}

‎packages/client/src/adapters/websocket/rpc-link.test.ts‎

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import type { IncomingMessage } from 'node:http'
22
import type { AddressInfo } from 'node:net'
33

4-
import { AbortError, promiseWithResolvers } from '@orpc/shared'
4+
import { promiseWithResolvers } from '@orpc/shared'
55
import { decodePeerMessage, encodePeerMessage } from '@standard-server/peer'
66
import { WebSocketServer, WebSocket as WsWebSocket } from 'ws'
77

88
import { createORPCClient } from '../../client'
9+
import { ConnectionClosedError } from '../../error'
910
import { RPCLink } from './rpc-link'
1011

1112
beforeEach(() => {
@@ -309,7 +310,7 @@ describe('rpcLink', () => {
309310
await ws.close({ code: 4001, reason: 'server restart' })
310311

311312
await expect(orpc.ping('second')).rejects.toThrow(
312-
new AbortError('WebSocket closed (code 4001: server restart)'),
313+
new ConnectionClosedError('WebSocket closed (code 4001: server restart)'),
313314
)
314315
expect(ws.send).toHaveBeenCalledTimes(1)
315316
expect(connect).toHaveBeenCalledTimes(1)
@@ -326,7 +327,11 @@ describe('rpcLink', () => {
326327
)
327328
await ws.close()
328329

329-
await expect(promise).rejects.toThrow(new AbortError('WebSocket closed (code 1006: )'))
330+
await expect(promise).rejects.toThrow(
331+
new ConnectionClosedError('WebSocket closed (code 1006: )'),
332+
)
333+
await expect(promise).rejects.toBeInstanceOf(ConnectionClosedError)
334+
await expect(promise).rejects.toHaveProperty('name', 'ConnectionClosedError')
330335
expect(ws.send).toHaveBeenCalledTimes(0)
331336
})
332337

@@ -341,10 +346,10 @@ describe('rpcLink', () => {
341346
const orpc = createORPCClient(new RPCLink({ connect })) as any
342347

343348
await expect(orpc.ping('first')).rejects.toThrow(
344-
new AbortError('WebSocket is already closing or closed'),
349+
new ConnectionClosedError('WebSocket is already closing or closed'),
345350
)
346351
await expect(orpc.ping('second')).rejects.toThrow(
347-
new AbortError('WebSocket is already closing or closed'),
352+
new ConnectionClosedError('WebSocket is already closing or closed'),
348353
)
349354
expect(ws.send).toHaveBeenCalledTimes(0)
350355
expect(connect).toHaveBeenCalledTimes(1)
@@ -398,6 +403,31 @@ describe('rpcLink', () => {
398403
expect(connect).toHaveBeenCalledTimes(1)
399404
})
400405

406+
it('gives up when the socket is closing without a close reason and no attempts are left', async () => {
407+
const ws = createWs()
408+
const connect = vi.fn(() => ws)
409+
const orpc = createORPCClient(
410+
new RPCLink({
411+
connect,
412+
reconnect: { delay: () => 0, maxAttempts: 1 },
413+
}),
414+
) as any
415+
416+
orpc.ping('first').catch(() => {})
417+
await vi.waitFor(() => expect(ws.send).toHaveBeenCalledTimes(1))
418+
419+
ws.readyState = WEBSOCKET_CLOSING
420+
421+
const error = await orpc.ping('second').catch((error: unknown) => error)
422+
423+
expect(error).toBeInstanceOf(ConnectionClosedError)
424+
expect(error).toMatchObject({
425+
message: 'WebSocket reconnect failed after 1 attempt(s)',
426+
cause: new ConnectionClosedError('WebSocket is already closing or closed'),
427+
})
428+
expect(connect).toHaveBeenCalledTimes(1)
429+
})
430+
401431
it('fails every call waiting on a reconnect cycle that gives up', async () => {
402432
const connect = vi.fn(() => Promise.reject(new Error('temporary outage')))
403433
const orpc = createORPCClient(
@@ -487,7 +517,7 @@ describe('rpcLink', () => {
487517

488518
await firstSocket.close()
489519

490-
const error = new AbortError('WebSocket reconnect stopped after 3 total attempt(s)')
520+
const error = new ConnectionClosedError('WebSocket reconnect stopped after 3 total attempt(s)')
491521
await Promise.all(
492522
['second', 'third'].map((input) => expect(orpc.ping(input)).rejects.toThrow(error)),
493523
)
@@ -781,13 +811,15 @@ describe('rpcLink', () => {
781811
return result
782812
}
783813

784-
const closed = new AbortError('WebSocket closed (code 4001: unauthorized)')
814+
const closed = new ConnectionClosedError('WebSocket closed (code 4001: unauthorized)')
785815
await expect(call('1')).resolves.toEqual(closed)
786816
await expect(call('2')).resolves.toEqual(closed)
787817

788818
const errors = await Promise.all([call('3'), call('4')])
789819
for (const error of errors) {
790-
expect(error).toEqual(new AbortError('WebSocket reconnect failed after 2 attempt(s)'))
820+
expect(error).toEqual(
821+
new ConnectionClosedError('WebSocket reconnect failed after 2 attempt(s)'),
822+
)
791823
expect(error.cause).toEqual(closed)
792824
}
793825
expect(connect).toHaveBeenCalledTimes(2)
@@ -856,7 +888,7 @@ describe('rpcLink', () => {
856888
const orpc = createORPCClient(new RPCLink({ connect: () => new WsWebSocket(url) })) as any
857889

858890
await expect(orpc.ping('input')).rejects.toThrow(
859-
new AbortError('WebSocket closed (code 1006: )'),
891+
new ConnectionClosedError('WebSocket closed (code 1006: )'),
860892
)
861893
})
862894

@@ -893,7 +925,7 @@ describe('rpcLink', () => {
893925
const orpc = createORPCClient(new RPCLink({ connect: () => new WsWebSocket(url) })) as any
894926

895927
await expect(orpc.ping('input')).rejects.toThrow(
896-
new AbortError('WebSocket closed (code 1006: )'),
928+
new ConnectionClosedError('WebSocket closed (code 1006: )'),
897929
)
898930
})
899931
})

‎packages/client/src/adapters/websocket/transport.ts‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import type { Promisable } from '@orpc/shared'
22
import {
3-
AbortError,
43
loadBytes,
54
promiseWithResolvers,
65
runWithSignal,
@@ -17,6 +16,7 @@ import {
1716
isServerPeerSendMessage,
1817
} from '@standard-server/peer'
1918

19+
import { ConnectionClosedError } from '../../error'
2020
import type { ClientContext, ClientOptions } from '../../types'
2121
import type { StandardLinkTransport } from '../standard/index'
2222

@@ -145,7 +145,7 @@ interface Connection {
145145
websocket: WebSocketLike
146146
peer: ClientPeer
147147
isHealthy: () => boolean
148-
closeReason: () => undefined | AbortError
148+
closeReason: () => undefined | ConnectionClosedError
149149
}
150150

151151
export class WebSocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
@@ -210,15 +210,18 @@ export class WebSocketLinkTransport<T extends ClientContext> implements Standard
210210
}
211211

212212
if (this.totalAttempt >= this.reconnectMaxTotalAttempt) {
213-
throw new AbortError(
213+
throw new ConnectionClosedError(
214214
`WebSocket reconnect stopped after ${this.totalAttempt} total attempt(s)`,
215215
)
216216
}
217217

218218
this.current = (async () => {
219219
// Rejecting `current` lets the `.catch` below fail every call waiting on it
220220
if (this.attempt >= this.reconnectMaxAttempt) {
221-
throw resolved?.closeReason() ?? new AbortError('WebSocket is already closing or closed')
221+
throw (
222+
resolved?.closeReason() ??
223+
new ConnectionClosedError('WebSocket is already closing or closed')
224+
)
222225
}
223226

224227
this.totalAttempt += 1
@@ -236,10 +239,10 @@ export class WebSocketLinkTransport<T extends ClientContext> implements Standard
236239
websocket.readyState !== WEBSOCKET_CONNECTING &&
237240
websocket.readyState !== WEBSOCKET_OPEN
238241
) {
239-
throw new AbortError('WebSocket is already closing or closed')
242+
throw new ConnectionClosedError('WebSocket is already closing or closed')
240243
}
241244

242-
let closeReason: undefined | AbortError
245+
let closeReason: undefined | ConnectionClosedError
243246
let closedAt: undefined | number
244247
let receivedMessage = false
245248

@@ -282,7 +285,9 @@ export class WebSocketLinkTransport<T extends ClientContext> implements Standard
282285
)
283286

284287
websocket.addEventListener('close', async (event) => {
285-
closeReason = new AbortError(`WebSocket closed (code ${event.code}: ${event.reason})`)
288+
closeReason = new ConnectionClosedError(
289+
`WebSocket closed (code ${event.code}: ${event.reason})`,
290+
)
286291
closedAt = Date.now()
287292
connectingResolvers?.resolve()
288293
await peer.close(closeReason)
@@ -320,7 +325,7 @@ export class WebSocketLinkTransport<T extends ClientContext> implements Standard
320325
const attempt = this.attempt
321326
this.attempt = 0
322327
this.current = undefined
323-
throw new AbortError(`WebSocket reconnect failed after ${attempt} attempt(s)`, {
328+
throw new ConnectionClosedError(`WebSocket reconnect failed after ${attempt} attempt(s)`, {
324329
cause: error,
325330
})
326331
}

‎packages/client/src/error.test.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { NullProtoObj } from '@orpc/shared'
1+
import { isAbortError, NullProtoObj } from '@orpc/shared'
22

3-
import { MalformedResponseError, ORPCError, ResponseError } from './error'
3+
import { ConnectionClosedError, MalformedResponseError, ORPCError, ResponseError } from './error'
44

55
describe('oRPCError', () => {
66
it('works', () => {
@@ -137,6 +137,19 @@ describe('responseError', () => {
137137
})
138138
})
139139

140+
describe('connectionClosedError', () => {
141+
it('is a distinct error that is not named like an abort', () => {
142+
const cause = new Error('cause')
143+
const error = new ConnectionClosedError('closed', { cause })
144+
145+
expect(error).toBeInstanceOf(Error)
146+
expect(error.name).toBe('ConnectionClosedError')
147+
expect(error.message).toBe('closed')
148+
expect(error.cause).toBe(cause)
149+
expect(isAbortError(error)).toBe(false)
150+
})
151+
})
152+
140153
describe('malformedResponseError', () => {
141154
it('works', () => {
142155
const response = {

‎packages/client/src/error.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,13 @@ export class ResponseError extends Error {
192192
}
193193
}
194194

195+
/**
196+
* Error thrown by WebSocket and MessagePort links when the connection is closed or lost.
197+
*/
198+
export class ConnectionClosedError extends Error {
199+
override readonly name = 'ConnectionClosedError'
200+
}
201+
195202
export interface MalformedResponseErrorOptions extends ResponseErrorOptions {
196203
/**
197204
* @default inferred from the response body or status

‎packages/client/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ export {
5454
* @deprecated Use `streamToAsyncIteratorObject` instead.
5555
*/
5656
streamToAsyncIteratorObject as streamToEventIterator,
57+
TimeoutError,
5758
} from '@orpc/shared'
5859

5960
export type {

‎packages/client/src/plugins/retry.test.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { withEventMeta } from '@standard-server/core'
44

55
import type { StandardLinkCodec, StandardLinkTransport } from '../adapters/standard/index'
66
import { StandardLink } from '../adapters/standard/index'
7-
import { MalformedResponseError, ORPCError, ResponseError } from '../error'
7+
import { ConnectionClosedError, MalformedResponseError, ORPCError, ResponseError } from '../error'
88
import type { RetryLinkPluginContext } from './retry'
99
import { isRetryableError, RetryLinkPlugin } from './retry'
1010

@@ -66,12 +66,14 @@ describe('isRetryableError', () => {
6666
expect(isRetryableError(new MalformedResponseError({ response }))).toBe(expected)
6767
})
6868

69-
it.each([new ORPCError('BAD_REQUEST'), new TypeError('Failed to fetch'), 'FAIL'])(
70-
'errors without a response -> true (%s)',
71-
(error) => {
72-
expect(isRetryableError(error)).toBe(true)
73-
},
74-
)
69+
it.each([
70+
new ORPCError('BAD_REQUEST'),
71+
new TypeError('Failed to fetch'),
72+
new ConnectionClosedError('WebSocket closed'),
73+
'FAIL',
74+
])('errors without a response -> true (%s)', (error) => {
75+
expect(isRetryableError(error)).toBe(true)
76+
})
7577
})
7678

7779
describe('retryLinkPlugin', () => {

0 commit comments

Comments
 (0)