Skip to content

Commit f97a6cd

Browse files
committed
feat: use custom error instance
1 parent 0561bd9 commit f97a6cd

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

src/index.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,13 @@ import type { QuansyncAwaitableGenerator, QuansyncFn, QuansyncGenerator, Quansyn
33
export * from './types'
44

55
export const GET_IS_ASYNC = Symbol.for('quansync.getIsAsync')
6-
const ERROR_PROMISE_IN_SYNC = '[Quansync] Yielded an unexpected promise in sync context'
6+
7+
export class QuansyncError extends Error {
8+
constructor(message = 'Unexpected promise in sync context') {
9+
super(message)
10+
this.name = 'QuansyncError'
11+
}
12+
}
713

814
function isThenable<T>(value: any): value is Promise<T> {
915
return value && typeof value === 'object' && typeof value.then === 'function'
@@ -37,7 +43,7 @@ function fromPromise<T>(promise: Promise<T> | T): QuansyncFn<T, []> {
3743
async: () => Promise.resolve(promise),
3844
sync: () => {
3945
if (isThenable(promise))
40-
throw new Error(ERROR_PROMISE_IN_SYNC)
46+
throw new QuansyncError()
4147
return promise
4248
},
4349
})
@@ -49,7 +55,7 @@ function unwrapYield(value: any, isAsync?: boolean): any {
4955
if (isQuansyncGenerator(value))
5056
return isAsync ? iterateAsync(value) : iterateSync(value)
5157
if (!isAsync && isThenable(value))
52-
throw new Error(ERROR_PROMISE_IN_SYNC)
58+
throw new QuansyncError()
5359
return value
5460
}
5561

test/index.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ it('yield optional promise', async () => {
9494
transform: async (code: string) => `${code}1`,
9595
},
9696
], 'foo'),
97-
).toThrowErrorMatchingInlineSnapshot(`[Error: [Quansync] Yielded an unexpected promise in sync context]`)
97+
).toThrowErrorMatchingInlineSnapshot(`[QuansyncError: Unexpected promise in sync context]`)
9898

9999
await expect(
100100
transform.async([
@@ -114,7 +114,7 @@ it('yield promise', async () => {
114114
})
115115

116116
expect(() => run.sync('foo'))
117-
.toThrowErrorMatchingInlineSnapshot(`[Error: [Quansync] Yielded an unexpected promise in sync context]`)
117+
.toThrowErrorMatchingInlineSnapshot(`[QuansyncError: Unexpected promise in sync context]`)
118118
await expect(run.async('foo')).resolves.toBe('foo')
119119
})
120120

0 commit comments

Comments
 (0)