ajv-validator / ajv

The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)
https://ajv.js.org
MIT License
13.71k stars 872 forks source link

`regexp` should be wrapped in try/catchs #2477

Open RedHatter opened 1 month ago

RedHatter commented 1 month ago

What version of Ajv you are you using? 8.17.1

What problem do you want to solve? Tracking down invalid regex.

What do you think is the correct solution to problem? An invalid regex in the schema (in my case ^[0-9]{2-4}) throws an error without any indication where in the schema or what pattern failed. When you have a large schema this makes it difficult to track down exactly where the bad pattern is. There's a todo in the code about this.

This can be somewhat mitigated by use the regExp option.

new Ajv({
  code: {
    regExp: (pattern: string, u: string) => {
      try {
        return new RegExp(pattern, u)
      } catch (e) {
        console.error('Bad RegExp: ', pattern, e)
      }
    },
  }
})

However this only displays the bad pattern not where in the schema it's used.

Will you be able to implement it? No.

jasoniangreen commented 1 month ago

Hi @RedHatter, you are right, it's not very helpful in this situation. Thanks for sharing the mitigating approach. I will try and raise it with the author sometime but there are other priorities at the moment, though I am curious why it wasn't just wrapped at the time. There might be some good reason why not.

I'll keep an eye on this issue too to see how requested a change in this area is.

jasoniangreen commented 1 month ago

I'll try and find time to fit in a fix on this but have other priorities so I'm also happy to review a PR by someone else.

jasoniangreen commented 1 month ago

Sorry @RedHatter but I want to check something. You said that the existing error doesn't show you the failing pattern but I get an error message like this:

SyntaxError: Invalid regular expression: /^[0-9]{2-4}/: Incomplete quantifier
RedHatter commented 1 month ago

The exact error message I got was

Uncaught SyntaxError: incomplete quantifier in regular expression

Note that this was in firefox. I didn't check the error message in any other browsers at the time.

jasoniangreen commented 1 month ago

Ah I see. It seems in node (at least version 18) you get a more useful message that includes the expression. I'll still keep it in mind because we could include the json schema path of the expression.