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

[Question] - Documentation on $error in schemas

Open CGSeb opened this issue 3 years ago • 2 comments

Hi, I see that we can specify a $error in a schema, but I can't find any documentation about it and how to use it.

{
    "type": "object",
    "properties":  {
        "name": {
            "type": "string",
            "$error":  {
                 "type": "The name should be a string"
            }
        }
    }
}

Am I missing something?

CGSeb avatar Dec 10 '21 16:12 CGSeb

Unfortunately we don't have docs for $error yet. However, this comment contains an example https://github.com/opis/json-schema/issues/80#issuecomment-832103630

$error can be a string or an object. If it is a string then no matter what keyword has error the message will always be the same.

{
   "type": "number",
   "minimum": 18,
   "maximum": 65,
   "$error": "Number must be in range 18-65"
}

If schema is invalid the error will always be "Number must be in range 18-65".

If $error is an object, then the keys represent the keyword and the value the error message.

{
   "type": "number",
   "minimum": 18,
   "maximum": 65,
   "$error": {
       "minimum": "Too young",
       "maximum": "Too old"
   }
}

If the minimum keyword failed then the message is Too young, if the maximum keyword failed the message will be Too old. If other keyword failed (for example type) the default error message will be used. You can provide a custom fallback if you are not interested in all properties.

{
   "type": "number",
   "minimum": 18,
   "maximum": 65,
   "$error": {
       "minimum": "Too young",
       "*": "Invalid number"
   }
}

If the minimum keyword failed then the message is Too young otherwise the message is Invalid number.

These are basic examples on how to use the $error keyword. Also keep in mind that this is something specific to opis/json-schema, it is an attempt at providing user defined error messages embedding them in json-schemas.

sorinsarca avatar Dec 10 '21 17:12 sorinsarca

Ok thank you, I have a case with some anyOf and some const for a dropdown select and it yields at me for every line of the anyOf, but I will do some testing with what you just said :)

CGSeb avatar Dec 10 '21 19:12 CGSeb