or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-validation.mderror-handling.mdformat-validation.mdindex.mdtype-checking.mdvalidator-creation.mdvalidators.md

error-handling.mddocs/

0

# Error Handling

1

2

Comprehensive error reporting system providing detailed validation failure information, error organization utilities, and tools for finding the most relevant errors in complex validation scenarios.

3

4

## Capabilities

5

6

### ValidationError

7

8

The primary exception raised when JSON Schema validation fails, containing detailed information about the validation failure.

9

10

```python { .api }

11

class ValidationError(Exception):

12

"""

13

Exception raised when validation fails.

14

15

Attributes:

16

- message: Human-readable error message

17

- path: Path to the failing instance property

18

- schema_path: Path to the failing schema property

19

- context: List of sub-errors for complex validations

20

- validator: The validator keyword that failed

21

- validator_value: The schema value for the failed validator

22

- instance: The instance value that failed validation

23

- schema: The schema that validation failed against

24

- parent: Parent error for nested validations

25

"""

26

27

def __init__(self,

28

message,

29

validator=None,

30

path=(),

31

cause=None,

32

context=(),

33

validator_value=None,

34

instance=None,

35

schema=None,

36

schema_path=(),

37

parent=None,

38

type_checker=None):

39

"""

40

Initialize validation error.

41

42

Parameters:

43

- message: Error description

44

- validator: Validator keyword that failed

45

- path: Path to failing instance property

46

- cause: Underlying exception that caused the error

47

- context: Sub-errors for complex validations

48

- validator_value: Schema value for failed validator

49

- instance: Instance value that failed

50

- schema: Schema that failed

51

- schema_path: Path to failing schema property

52

- parent: Parent error for nested validations

53

- type_checker: Type checker used during validation

54

"""

55

56

@property

57

def absolute_path(self):

58

"""

59

Absolute path to the failing instance property.

60

61

Returns:

62

- deque: Complete path from root to failing property

63

"""

64

65

@property

66

def absolute_schema_path(self):

67

"""

68

Absolute path to the failing schema property.

69

70

Returns:

71

- deque: Complete path from root to failing schema property

72

"""

73

74

@property

75

def json_path(self):

76

"""

77

JSONPath expression for the failing instance property.

78

79

Returns:

80

- str: JSONPath expression

81

"""

82

```

83

84

### SchemaError

85

86

Exception raised when a schema itself is invalid.

87

88

```python { .api }

89

class SchemaError(Exception):

90

"""

91

Exception raised when a schema is invalid.

92

93

Inherits all attributes and methods from ValidationError.

94

"""

95

```

96

97

### ErrorTree

98

99

Hierarchical organization of validation errors for complex schemas with nested validation rules.

100

101

```python { .api }

102

class ErrorTree:

103

"""

104

Tree structure for organizing validation errors.

105

106

Provides dictionary-like and attribute-like access to errors

107

organized by the path where they occurred.

108

"""

109

110

def __init__(self, errors=()):

111

"""

112

Initialize error tree.

113

114

Parameters:

115

- errors: Iterable of ValidationError objects

116

"""

117

118

@property

119

def errors(self):

120

"""

121

Direct errors at this tree node.

122

123

Returns:

124

- frozenset: Errors that occurred at this exact path

125

"""

126

127

@property

128

def total_errors(self):

129

"""

130

Total number of errors in tree and all subtrees.

131

132

Returns:

133

- int: Total error count

134

"""

135

136

def __getitem__(self, index):

137

"""

138

Access subtree by path component.

139

140

Parameters:

141

- index: Path component (string or integer)

142

143

Returns:

144

- ErrorTree: Subtree for the given path component

145

"""

146

147

def __contains__(self, index):

148

"""

149

Check if path component has errors.

150

151

Parameters:

152

- index: Path component to check

153

154

Returns:

155

- bool: True if path has errors

156

"""

157

```

158

159

### Error Analysis Functions

160

161

Utilities for finding the most relevant errors from complex validation results.

162

163

```python { .api }

164

def best_match(errors, key=None):

165

"""

166

Find the most relevant error from a collection of errors.

167

168

Parameters:

169

- errors: Iterable of ValidationError objects

170

- key: Function to compute error relevance (optional)

171

172

Returns:

173

- ValidationError: Most relevant error

174

"""

175

176

def by_relevance(weak=WEAK_MATCHES, strong=STRONG_MATCHES):

177

"""

178

Create error relevance function for best_match.

179

180

Parameters:

181

- weak: Set of weakly matching validator keywords

182

- strong: Set of strongly matching validator keywords

183

184

Returns:

185

- function: Relevance function for error comparison

186

"""

187

188

# Pre-configured relevance function

189

relevance: callable

190

"""

191

Pre-configured key function for sorting errors by relevance.

192

193

This is a pre-configured instance of by_relevance() that can be used

194

directly with sorted() or as the key parameter for best_match().

195

196

Example:

197

sorted(validator.iter_errors(instance), key=relevance)

198

"""

199

```

200

201

### Additional Exception Types

202

203

Specialized exceptions for specific error conditions.

204

205

```python { .api }

206

class UndefinedTypeCheck(Exception):

207

"""Raised when an undefined type is used in type checking."""

208

209

class UnknownType(Exception):

210

"""Raised when an unknown type name is encountered."""

211

212

class FormatError(Exception):

213

"""Raised when format validation fails."""

214

```

215

216

## Usage Examples

217

218

### Basic Error Handling

219

220

```python

221

from jsonschema import Draft202012Validator, ValidationError

222

223

schema = {

224

"type": "object",

225

"properties": {

226

"name": {"type": "string"},

227

"age": {"type": "integer", "minimum": 0}

228

},

229

"required": ["name", "age"]

230

}

231

232

validator = Draft202012Validator(schema)

233

invalid_data = {"name": 123} # Wrong type for name, missing age

234

235

try:

236

validator.validate(invalid_data)

237

except ValidationError as e:

238

print(f"Error: {e.message}")

239

print(f"Path: {'.'.join(str(p) for p in e.path)}")

240

print(f"Failed validator: {e.validator}")

241

print(f"Schema path: {'.'.join(str(p) for p in e.schema_path)}")

242

```

243

244

### Collecting All Errors

245

246

```python

247

from jsonschema import Draft202012Validator

248

249

validator = Draft202012Validator(schema)

250

invalid_data = {"name": 123, "age": -5} # Multiple errors

251

252

errors = list(validator.iter_errors(invalid_data))

253

print(f"Found {len(errors)} errors:")

254

255

for error in errors:

256

path = '.'.join(str(p) for p in error.path) if error.path else 'root'

257

print(f" - {path}: {error.message}")

258

```

259

260

### Using ErrorTree

261

262

```python

263

from jsonschema import Draft202012Validator, ErrorTree

264

265

schema = {

266

"type": "object",

267

"properties": {

268

"users": {

269

"type": "array",

270

"items": {

271

"type": "object",

272

"properties": {

273

"name": {"type": "string"},

274

"email": {"type": "string", "format": "email"}

275

},

276

"required": ["name", "email"]

277

}

278

}

279

}

280

}

281

282

validator = Draft202012Validator(schema)

283

invalid_data = {

284

"users": [

285

{"name": "Alice"}, # Missing email

286

{"email": "invalid-email"} # Missing name, invalid email

287

]

288

}

289

290

errors = validator.iter_errors(invalid_data)

291

tree = ErrorTree(errors)

292

293

# Access errors by path

294

if 'users' in tree:

295

users_tree = tree['users']

296

if 0 in users_tree:

297

print("Errors in first user:", users_tree[0].errors)

298

if 1 in users_tree:

299

print("Errors in second user:", users_tree[1].errors)

300

301

print(f"Total errors: {tree.total_errors}")

302

```

303

304

### Finding the Most Relevant Error

305

306

```python

307

from jsonschema import Draft202012Validator, best_match

308

309

schema = {

310

"anyOf": [

311

{"type": "string"},

312

{"type": "number"},

313

{"type": "object", "properties": {"name": {"type": "string"}}}

314

]

315

}

316

317

validator = Draft202012Validator(schema)

318

invalid_data = {"name": 123} # Object with wrong property type

319

320

errors = list(validator.iter_errors(invalid_data))

321

most_relevant = best_match(errors)

322

323

print(f"Most relevant error: {most_relevant.message}")

324

```

325

326

### JSON Path Information

327

328

```python

329

from jsonschema import Draft202012Validator

330

331

schema = {

332

"type": "object",

333

"properties": {

334

"data": {

335

"type": "array",

336

"items": {"type": "string"}

337

}

338

}

339

}

340

341

validator = Draft202012Validator(schema)

342

invalid_data = {"data": ["valid", 123, "also_valid"]}

343

344

for error in validator.iter_errors(invalid_data):

345

print(f"JSONPath: {error.json_path}")

346

print(f"Error: {error.message}")

347

```

348

349

### Context Errors

350

351

```python

352

from jsonschema import Draft202012Validator

353

354

schema = {

355

"oneOf": [

356

{"type": "string", "minLength": 5},

357

{"type": "number", "minimum": 10}

358

]

359

}

360

361

validator = Draft202012Validator(schema)

362

invalid_data = "hi" # Too short for string, not a number

363

364

errors = list(validator.iter_errors(invalid_data))

365

for error in errors:

366

print(f"Main error: {error.message}")

367

if error.context:

368

print("Context errors:")

369

for ctx_error in error.context:

370

print(f" - {ctx_error.message}")

371

```