@@ -405,3 +405,69 @@ to guess the most relevant error in a given bunch.
405
405
406
406
.. autofunction:: by_relevance
407
407
:noindex:
408
+
409
+ Human-Friendly Error Messages
410
+ ----------------------------
411
+
412
+ Sometimes the default validation error messages can be too technical for end users.
413
+ To help with this, jsonschema provides a way to convert validation errors into more
414
+ human-friendly messages.
415
+
416
+ .. testcode::
417
+
418
+ from jsonschema import human_validate
419
+
420
+ try:
421
+ human_validate({"age": "twenty"}, {"properties": {"age": {"type": "integer"}}})
422
+ except Exception as e:
423
+ print(e)
424
+
425
+ outputs:
426
+
427
+ .. testoutput::
428
+
429
+ Expected whole number, but got "twenty" at '$.age'
430
+
431
+ You can use these functions to work with human-friendly validation errors:
432
+
433
+ .. function:: human_validate(instance, schema, cls=None, *args, **kwargs)
434
+
435
+ Like :func: `jsonschema.validate `, but with human-friendly error messages.
436
+
437
+ .. function:: humanize_error(error)
438
+
439
+ Convert a ValidationError into a user-friendly message.
440
+
441
+ .. function:: enable_human_errors(validator_class)
442
+
443
+ Modify a validator class to use human-friendly error messages.
444
+
445
+ .. function:: create_human_validator(schema, *args, **kwargs)
446
+
447
+ Create a validator that uses human-friendly error messages.
448
+
449
+ .. function:: apply_to_all_validators()
450
+
451
+ Patch all validator classes to use human-friendly error messages.
452
+
453
+ For example, you could convert a technical error into a user-friendly one:
454
+
455
+ .. testcode::
456
+
457
+ from jsonschema import validate, humanize_error
458
+
459
+ schema = {"type": "object", "required": ["name", "email"]}
460
+ data = {"name": "John"}
461
+
462
+ try:
463
+ validate(data, schema)
464
+ except Exception as e:
465
+ print("Technical error:", e)
466
+ print("User-friendly error:", humanize_error(e))
467
+
468
+ outputs:
469
+
470
+ .. testoutput::
471
+
472
+ Technical error: 'email' is a required property
473
+ User-friendly error: Missing required field: 'email'
0 commit comments