Skip to content

Commit c5ab90e

Browse files
authored
feat: allow custom errors in $close (#23)
1 parent 68f891f commit c5ab90e

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

src/index.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ export interface BirpcGroupFn<T> {
109109

110110
export type BirpcReturn<RemoteFunctions, LocalFunctions = Record<string, never>> = {
111111
[K in keyof RemoteFunctions]: BirpcFn<RemoteFunctions[K]>
112-
} & { $functions: LocalFunctions, $close: () => void }
112+
} & { $functions: LocalFunctions, $close: (error?: Error) => void }
113113

114114
export type BirpcGroupReturn<RemoteFunctions> = {
115115
[K in keyof RemoteFunctions]: BirpcGroupFn<RemoteFunctions[K]>
@@ -266,10 +266,10 @@ export function createBirpc<RemoteFunctions = Record<string, never>, LocalFuncti
266266
},
267267
}) as BirpcReturn<RemoteFunctions, LocalFunctions>
268268

269-
function close() {
269+
function close(error?: Error) {
270270
closed = true
271271
rpcPromiseMap.forEach(({ reject, method }) => {
272-
reject(new Error(`[birpc] rpc is closed, cannot call "${method}"`))
272+
reject(error || new Error(`[birpc] rpc is closed, cannot call "${method}"`))
273273
})
274274
rpcPromiseMap.clear()
275275
off(onMessage)

test/close.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,24 @@ it('stops the rpc promises', async () => {
2323
await promise
2424
await expect(() => rpc.hello()).rejects.toThrow('[birpc] rpc is closed, cannot call "hello"')
2525
})
26+
27+
it('stops the rpc promises with a custom message', async () => {
28+
expect.assertions(1)
29+
const rpc = createBirpc<{ hello: () => string }>({}, {
30+
on() {},
31+
post() {},
32+
})
33+
const promise = rpc.hello().then(
34+
() => {
35+
throw new Error('Promise should not resolve')
36+
},
37+
(err) => {
38+
// Promise should reject
39+
expect(err.message).toBe('Custom error')
40+
},
41+
)
42+
nextTick(() => {
43+
rpc.$close(new Error('Custom error'))
44+
})
45+
await promise
46+
})

0 commit comments

Comments
 (0)