Skip to content

Commit 40ee074

Browse files
authored
fix: $close to set original error in .cause (#25)
1 parent 3a78f95 commit 40ee074

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

src/index.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -269,10 +269,17 @@ export function createBirpc<RemoteFunctions = Record<string, never>, LocalFuncti
269269
},
270270
}) as BirpcReturn<RemoteFunctions, LocalFunctions>
271271

272-
function close(error?: Error) {
272+
function close(customError?: Error) {
273273
closed = true
274274
rpcPromiseMap.forEach(({ reject, method }) => {
275-
reject(error || new Error(`[birpc] rpc is closed, cannot call "${method}"`))
275+
const error = new Error(`[birpc] rpc is closed, cannot call "${method}"`)
276+
277+
if (customError) {
278+
customError.cause ??= error
279+
return reject(customError)
280+
}
281+
282+
reject(error)
276283
})
277284
rpcPromiseMap.clear()
278285
off(onMessage)

test/close.test.ts

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ it('stops the rpc promises', async () => {
2525
})
2626

2727
it('stops the rpc promises with a custom message', async () => {
28-
expect.assertions(1)
28+
expect.assertions(2)
2929
const rpc = createBirpc<{ hello: () => string }>({}, {
3030
on() {},
3131
post() {},
@@ -37,10 +37,39 @@ it('stops the rpc promises with a custom message', async () => {
3737
(err) => {
3838
// Promise should reject
3939
expect(err.message).toBe('Custom error')
40+
41+
// Original error should be present
42+
expect(err.cause.message).toBe('[birpc] rpc is closed, cannot call "hello"')
4043
},
4144
)
4245
nextTick(() => {
4346
rpc.$close(new Error('Custom error'))
4447
})
4548
await promise
4649
})
50+
51+
it('custom error\'s cause is not overwritten', async () => {
52+
expect.assertions(2)
53+
const rpc = createBirpc<{ hello: () => string }>({}, {
54+
on() {},
55+
post() {},
56+
})
57+
const promise = rpc.hello().then(
58+
() => {
59+
throw new Error('Promise should not resolve')
60+
},
61+
(err) => {
62+
// Promise should reject
63+
expect(err.message).toBe('Custom error')
64+
65+
// Custom error cause should be present
66+
expect(err.cause.message).toBe('Custom cause')
67+
},
68+
)
69+
nextTick(() => {
70+
const error = new Error('Custom error')
71+
error.cause = new Error('Custom cause')
72+
rpc.$close(error)
73+
})
74+
await promise
75+
})

0 commit comments

Comments
 (0)