schema-enforcer icon indicating copy to clipboard operation
schema-enforcer copied to clipboard

Custom Error Messages for Schema Failures

Open aggle-baggle opened this issue 3 years ago • 2 comments

Environment

  • Python version: 3.9.7
  • schema-enforcer version: 1.1.5

It would be great to have the option of custom error messages for schema failures and not just custom validation failures. For example when using the pattern keyword in a schema the error message returned contains the regular expression used which for some users may not be that helpful (if they are not familiar with regex for example). Instead having the option to define a custom error message in the schema itself for a property would be great.

Proposed Functionality

Currently a user can construct a schema using the pattern keyword and a regular expression:

fqdn:
  type: string
  pattern: (?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$)
   

If a value is supplied that does not match the regular expression, the error message returned is:

FAIL | [ERROR] '-host.test.com' does not match '(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$)' [FILE] .//test.yml [PROPERTY] fqdn

However if a key was introduced to define a custom message for this property, the schema could look like this:

fqdn:
  type: string
  pattern: (?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$)
  errMessage: "'$fqdn' is not a valid FQDN; please refer to: docs-url"

Schema Enforcer could then return the message as such:

FAIL | [ERROR] '-host.test.com' is not a valid FQDN; please refer to: docs-url [FILE] .//test.yml [PROPERTY] fqdn

Use Case

A good example would be a regex for an FQDN as descried above. Regex can be long and complicated and overwhelming to a user who is not familiar with its syntax. Instead a custom error message that refers the user to documentation would be a good way to encourage best practice and good docs.

EDIT: I'm aware that a custom validator could be written to do the regex check and return the custom error message however the added overhead could be avoided by introducing this feature.

It seems to be a fairly common requirement and the following Stack Overflow link contains one example of how this was implemented: https://stackoverflow.com/questions/25902635/python-jsonschema-package-to-validate-schema-and-custom-error-messages

aggle-baggle avatar Dec 20 '22 10:12 aggle-baggle

This is a great idea, moves complexity away from the user.

PhillSimonds avatar Dec 20 '22 15:12 PhillSimonds

Thank you @PhillSimonds, I've been looking at how to implement it with a colleague, hopefully have an MR soon!

aggle-baggle avatar Dec 20 '22 15:12 aggle-baggle