diff --git a/src/error.ts b/src/error.ts index 4002525..e5277cc 100644 --- a/src/error.ts +++ b/src/error.ts @@ -18,3 +18,15 @@ export default class PowerGuardError extends Error { this.details = details; } } + +export class PowerGuardKeyError extends Error { + key: string; + gut: PowerGuardError; + + constructor(key: string, gut: PowerGuardError) { + super(`Guard "${key}" failed: ${gut.message}`); + + this.key = key; + this.gut = gut; + } +} diff --git a/src/index.ts b/src/index.ts index 5e27113..a23a777 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ import { isObject } from './types'; import { GuardFunction } from './global'; -import PowerGuardError from './error'; +import PowerGuardError, { PowerGuardKeyError } from './error'; export type DataConfig = { [key: string]: GuardFunction; @@ -10,7 +10,7 @@ export type GuardedData = { [key in keyof T]: ReturnType; }; -export const guard = (config: T): GuardFunction> => ( +const guard = (config: T): GuardFunction> => ( data: unknown, ) => { if (!isObject(data)) { @@ -23,7 +23,14 @@ export const guard = (config: T): GuardFunction; + try { + guarded[key] = config[key](value) as ReturnType; + } catch (error) { + if (error instanceof PowerGuardError) { + throw new PowerGuardKeyError(String(key), error); + } + throw error; + } }); return guarded; @@ -35,7 +42,7 @@ export * from './global'; export * from './types'; -export { default as PowerGuardError } from './error'; +export { default as PowerGuardError, PowerGuardKeyError } from './error'; export { default as array } from './array'; diff --git a/tests/index.test.ts b/tests/index.test.ts index 3987456..e3c0478 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -1,5 +1,6 @@ -import guard, { number, string, enumGuard, boolean, array, PowerGuardError } from '../src'; +import guard, { number, string, enumGuard, boolean, array } from '../src'; import { expect } from 'chai'; +import PowerGuardError, { PowerGuardKeyError } from '../src/error'; enum Foo { key1 = 'key1', @@ -50,7 +51,7 @@ describe('Power guard', () => { bla: 1, bnd: [{ foo: '123' }], }), - ).throws(PowerGuardError); + ).throws(PowerGuardKeyError); expect(() => guardFunc({ @@ -60,7 +61,7 @@ describe('Power guard', () => { bla: 1, bnd: [{ foo: 123 }], }), - ).throws(PowerGuardError); + ).throws(PowerGuardKeyError); expect(() => guardFunc(`{