Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions src/consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ interface ConsumerEvents<TResult> {
requeued: [id: string]
}

type ExtendedError = Error & { code?: string; toJSON?: () => Record<string, any> }

/**
* Consumer handles processing jobs from the queue
*/
Expand Down Expand Up @@ -209,7 +211,7 @@ export class Consumer<TPayload, TResult> extends EventEmitter<ConsumerEvents<TRe
// Clear visibility timer
clearTimeout(visibilityTimer)

const error = err as Error
const error = err as ExtendedError
const currentAttempts = attempts + 1

if (currentAttempts < maxAttempts) {
Expand All @@ -226,11 +228,15 @@ export class Consumer<TPayload, TResult> extends EventEmitter<ConsumerEvents<TRe
} else {
// Max retries exceeded - fail the job
const maxRetriesError = new MaxRetriesError(id, currentAttempts, error)
const serializedError = Buffer.from(JSON.stringify({
message: error.message,
code: (error as Error & { code?: string }).code,
stack: error.stack
}))
const serializedError = Buffer.from(JSON.stringify(
typeof error.toJSON === 'function'
? error.toJSON()
: {
message: error.message,
code: error.code,
stack: error.stack
}
))

await this.#storage.failJob(id, message, this.#workerId, serializedError, this.#resultTTL)

Expand Down
31 changes: 31 additions & 0 deletions test/queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,37 @@ describe('Queue', () => {
assert.strictEqual(status.state, 'completed')
assert.deepStrictEqual(status.result, { result: 42 })
})

it('should use error.toJSON() for failed job status when available', async () => {
class JsonError extends Error {
toJSON (): unknown {
return {
message: this.message,
code: 'CUSTOM_ERROR',
details: { source: 'toJSON' }
}
}
}

queue.execute(async () => {
throw new JsonError('Serialized by toJSON')
})

await queue.start()

const failedPromise = once(queue, 'failed')
await queue.enqueue('job-1', { value: 21 }, { maxAttempts: 1 })
await failedPromise

const status = await queue.getStatus('job-1')
assert.ok(status)
assert.strictEqual(status.state, 'failed')
assert.deepStrictEqual(status.error, {
message: 'Serialized by toJSON',
code: 'CUSTOM_ERROR',
details: { source: 'toJSON' }
})
})
})

describe('concurrency', () => {
Expand Down