From 187f0cfba79787ab6ed641ff10e8944adef8ad58 Mon Sep 17 00:00:00 2001 From: Vladislav Botvin Date: Fri, 17 Jan 2025 12:33:11 +0300 Subject: [PATCH] stringify contexified error --- index.ts | 40 ++++++++++++++++++++++++---------------- test.ts | 8 ++++---- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/index.ts b/index.ts index e943b76..718b85a 100644 --- a/index.ts +++ b/index.ts @@ -1,3 +1,5 @@ +import { inspect } from 'node:util' + type KeyedFunction = F & { key: K; mutable: boolean } export const pure = (key: K, fn: (ctx: C) => R): KeyedFunction R> => @@ -4862,10 +4864,13 @@ export function klubok(...fns: KeyedFunction[]) { 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 } + ) } })() ) @@ -4879,19 +4884,22 @@ export function klubok(...fns: KeyedFunction[]) { (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 }) ) diff --git a/test.ts b/test.ts index 02a0b41..a273679 100644 --- a/test.ts +++ b/test.ts @@ -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 () => { @@ -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' }/) })