Skip to content

Commit

Permalink
stringify contexified error
Browse files Browse the repository at this point in the history
  • Loading branch information
darky committed Jan 17, 2025
1 parent 68778ce commit 187f0cf
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 20 deletions.
40 changes: 24 additions & 16 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { inspect } from 'node:util'

type KeyedFunction<K extends string, F extends Function> = F & { key: K; mutable: boolean }

export const pure = <K extends string, C, R>(key: K, fn: (ctx: C) => R): KeyedFunction<K, (ctx: C) => R> =>
Expand Down Expand Up @@ -4862,10 +4864,13 @@ export function klubok(...fns: KeyedFunction<string, Function>[]) {
try {
return await Promise.resolve(fn(ctx)).then(resp => ({ ...ctx, [fn.key]: resp }))
} catch (error: any) {
throw {
error: error.stack ?? error.message ?? error,
ctx
}
throw inspect(
{
error: error.stack ?? error.message ?? error,
ctx,
},
{ depth: 3 }
)
}
})()
)
Expand All @@ -4879,19 +4884,22 @@ export function klubok(...fns: KeyedFunction<string, Function>[]) {
(only && only.length && !only.includes(fn.key))
? ctx
: (async () => {
try {
return await Promise.resolve(
mock && Reflect.has(mock, fn.key) && typeof Reflect.get(mock, fn.key) === 'function'
? Reflect.get(mock, fn.key)(ctx)
: fn(ctx)
).then(resp => ({ ...ctx, [fn.key]: resp }))
} catch(error: any) {
throw {
error: error.stack ?? error.message ?? error,
ctx
try {
return await Promise.resolve(
mock && Reflect.has(mock, fn.key) && typeof Reflect.get(mock, fn.key) === 'function'
? Reflect.get(mock, fn.key)(ctx)
: fn(ctx)
).then(resp => ({ ...ctx, [fn.key]: resp }))
} catch (error: any) {
throw inspect(
{
error: error.stack ?? error.message ?? error,
ctx,
},
{ depth: 3 }
)
}
}
})()
})()
),
Promise.resolve({ ...rootCtx, ...mock })
)
Expand Down
8 changes: 4 additions & 4 deletions test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,8 +337,8 @@ test('throwable error with context for production fn', async () => {
})
)
const err = await fn({ number: 1 }).catch(e => e)
assert.match(err.error, /^Error: test/)
assert.deepStrictEqual(err.ctx, { number: 1, incNumber: 2, strNumber: '2' })
assert.match(err, /error: 'Error: test/)
assert.match(err, /ctx: { number: 1, incNumber: 2, strNumber: '2' }/)
})

test('throwable error with context for test fn', async () => {
Expand All @@ -350,6 +350,6 @@ test('throwable error with context for test fn', async () => {
})
)
const err = await fn({ number: 1 }, {}, []).catch(e => e)
assert.match(err.error, /^Error: test/)
assert.deepStrictEqual(err.ctx, { number: 1, incNumber: 2, strNumber: '2' })
assert.match(err, /error: 'Error: test/)
assert.match(err, /ctx: { number: 1, incNumber: 2, strNumber: '2' }/)
})

0 comments on commit 187f0cf

Please sign in to comment.