Skip to content

Commit e43efdf

Browse files
authored
feat: add abortName option to override thrown error name (#98)
The `.name` property is more ideomatic than a `.code` property so allow overriding it via options.
1 parent 8dd8a87 commit e43efdf

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed

src/abort-error.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ export class AbortError extends Error {
22
type: string
33
code: string
44

5-
constructor (message?: string, code?: string) {
5+
constructor (message?: string, code?: string, name?: string) {
66
super(message ?? 'The operation was aborted')
77
this.type = 'aborted'
88
this.code = code ?? 'ABORT_ERR'
9+
this.name = name ?? 'AbortError'
910
}
1011
}

src/index.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ export interface Options<T> {
5353
onAbort?(source: Source<T>): void
5454
abortMessage?: string
5555
abortCode?: string
56+
abortName?: string
5657
returnOnAbort?: boolean
5758
}
5859

@@ -75,14 +76,14 @@ export function abortableSource <T> (source: Source<T>, signal: AbortSignal, opt
7576
let result: IteratorResult<T, any>
7677
try {
7778
if (signal.aborted) {
78-
const { abortMessage, abortCode } = opts
79-
throw new AbortError(abortMessage, abortCode)
79+
const { abortMessage, abortCode, abortName } = opts
80+
throw new AbortError(abortMessage, abortCode, abortName)
8081
}
8182

8283
const abort = new Promise<any>((resolve, reject) => { // eslint-disable-line no-loop-func
8384
nextAbortHandler = () => {
84-
const { abortMessage, abortCode } = opts
85-
reject(new AbortError(abortMessage, abortCode))
85+
const { abortMessage, abortCode, abortName } = opts
86+
reject(new AbortError(abortMessage, abortCode, abortName))
8687
}
8788
})
8889

test/index.spec.ts

+15
Original file line numberDiff line numberDiff line change
@@ -240,4 +240,19 @@ describe('abortable-iterator', () => {
240240
})())
241241
.to.eventually.be.rejected.with.property('type', 'aborted')
242242
})
243+
244+
it('should override abort error properties', async () => {
245+
const controller = new AbortController()
246+
controller.abort()
247+
248+
const err = await drain(abortableSource(forever(), controller.signal, {
249+
abortCode: 'custom code',
250+
abortMessage: 'custom message',
251+
abortName: 'custom name'
252+
})).catch(err => err)
253+
254+
expect(err).to.have.property('code', 'custom code')
255+
expect(err).to.have.property('message', 'custom message')
256+
expect(err).to.have.property('name', 'custom name')
257+
})
243258
})

0 commit comments

Comments
 (0)