From 4e3463d28d49397a246169a16246349cce518554 Mon Sep 17 00:00:00 2001 From: Jason Green Date: Wed, 7 Aug 2024 21:32:01 +0100 Subject: [PATCH] fix: include original error and add extra info --- lib/vocabularies/code.ts | 2 +- lib/vocabularies/validation/pattern.ts | 2 +- spec/issues/2477_informative_pattern_errors.spec.ts | 9 ++++++--- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/lib/vocabularies/code.ts b/lib/vocabularies/code.ts index 1710b4aa3..63ad9022d 100644 --- a/lib/vocabularies/code.ts +++ b/lib/vocabularies/code.ts @@ -100,7 +100,7 @@ export function usePattern({gen, it: {opts, errSchemaPath}}: KeywordCxt, pattern try { rx = new RegExp(pattern, u) } catch (e) { - throw new Error(`Invalid regular expression: ${pattern} at ${errSchemaPath}`) + throw new Error(`${(e as Error).message} | pattern ${pattern} at ${errSchemaPath}`) } rx = regExp(pattern, u) diff --git a/lib/vocabularies/validation/pattern.ts b/lib/vocabularies/validation/pattern.ts index 947cd72ec..e42997727 100644 --- a/lib/vocabularies/validation/pattern.ts +++ b/lib/vocabularies/validation/pattern.ts @@ -24,7 +24,7 @@ const def: CodeKeywordDefinition = { try { return new RegExp(${schemaCode}, ${u}) } catch (e) { - throw new Error('Invalid regular expression: ' + ${schemaCode} + ' at ' + ${it.errSchemaPath}) + throw new Error(e.message + ' | pattern ' + ${schemaCode} + ' at ' + ${it.errSchemaPath}) } })()` : usePattern(cxt, schema) diff --git a/spec/issues/2477_informative_pattern_errors.spec.ts b/spec/issues/2477_informative_pattern_errors.spec.ts index aa19ec401..facc6e450 100644 --- a/spec/issues/2477_informative_pattern_errors.spec.ts +++ b/spec/issues/2477_informative_pattern_errors.spec.ts @@ -13,7 +13,10 @@ describe("Invalid regexp patterns should throw more informative errors (issue #2 assert.throws( () => ajv.compile(rootSchema), (thrown: unknown) => { - assert.equal((thrown as Error).message, "Invalid regular expression: ^[0-9]{2-4} at #") + assert.equal( + (thrown as Error).message, + "Invalid regular expression: /^[0-9]{2-4}/: Incomplete quantifier | pattern ^[0-9]{2-4} at #" + ) return true } ) @@ -30,7 +33,7 @@ describe("Invalid regexp patterns should throw more informative errors (issue #2 (thrown: unknown) => { assert.equal( (thrown as Error).message, - "Invalid regular expression: ^[0-9]{2-4} at #/properties/foo" + "Invalid regular expression: /^[0-9]{2-4}/: Incomplete quantifier | pattern ^[0-9]{2-4} at #/properties/foo" ) return true } @@ -52,7 +55,7 @@ describe("Invalid regexp patterns should throw more informative errors (issue #2 (thrown: unknown) => { assert.equal( (thrown as Error).message, - "Invalid regular expression: ^[0-9]{2-4} at #/properties/string" + "Invalid regular expression: /^[0-9]{2-4}/: Incomplete quantifier | pattern ^[0-9]{2-4} at #/properties/string" ) return true }