@@ -47,6 +47,70 @@ raised or returned, depending on which method or function is used.
47
47
``schema_path `` and ``path `` of these errors will be relative to the
48
48
parent error.
49
49
50
+ These attributes can be clarified with a short example:
51
+
52
+ .. code-block :: python
53
+
54
+ >> > from jsonschema import Draft4Validator
55
+ >> > schema = {
56
+ ... " items" : {
57
+ ... " anyOf" : [
58
+ ... {" type" : " string" , " maxLength" : 2 },
59
+ ... {" type" : " integer" , " minimum" : 5 }
60
+ ... ]
61
+ ... }
62
+ ... }
63
+ >> > instance = [{}, 3 , " foo" ]
64
+ >> > v = Draft4Validator(schema)
65
+ >> > errors = list (v.iter_errors(instance))
66
+
67
+ The error messages in this situation are not very helpful on their own:
68
+
69
+ .. code-block :: python
70
+
71
+ >> > for e in errors:
72
+ ... print e.message
73
+ The instance is not valid under any of the given schemas
74
+ The instance is not valid under any of the given schemas
75
+ The instance is not valid under any of the given schemas
76
+
77
+ If we look at the :attr: `ValidationError.path ` attribute, we can find out which
78
+ elements in the instance we are validating are causing each of the errors. In
79
+ this example, :attr: `ValidationError.path ` will have only one element, which
80
+ will be the index in our list.
81
+
82
+ .. code-block :: python
83
+
84
+ >> > for e in errors:
85
+ ... print list (e.path)
86
+ [0 ]
87
+ [1 ]
88
+ [2 ]
89
+
90
+ Since our schema contained nested subschemas, it can be helpful to look at
91
+ the specific part of the instance and subschema that caused each of the errors.
92
+ This can be seen with the :attr: `ValidationError.instance ` and
93
+ :attr: `ValidationError.schema ` attributes.
94
+
95
+ With validators like ``anyOf ``, the :attr: `ValidationError.context` ` attribute
96
+ can be used to see the sub-errors which caused the failure. Since these errors
97
+ actually came from two separate subschemas, so it can be helpful to look at the
98
+ :attr: `ValidationError.schema_path ` attribute as well to see where exactly in
99
+ the schema each of these errors come from. In the case of sub-errors from the
100
+ :attr: `ValidationError.context ` attribute, this path will be relative to the
101
+ :attr: `ValidationError.schema_path ` of the parent error.
102
+
103
+ .. code-block :: python
104
+
105
+ >> > for e in errors:
106
+ ... for sube in e.context:
107
+ ... print list (sube.schema_path), sube
108
+ [0 , ' type' ] {} is not of type ' string'
109
+ [1 , ' type' ] {} is not of type ' integer'
110
+ [0 , ' type' ] 3 is not of type ' string'
111
+ [1 , ' minimum' ] 3.0 is less than the minimum of 5
112
+ [0 , ' maxLength' ] ' foo' is too long
113
+ [1 , ' type' ] ' foo' is not of type ' integer'
50
114
51
115
In case an invalid schema itself is encountered, a :exc: `SchemaError ` is
52
116
raised.
0 commit comments