Browse Source

Add __str__ methods to validation error classes for better debugging

Added human-readable string representations to RequestValidationError and
WebSocketRequestValidationError classes, consistent with the existing
ResponseValidationError implementation. This improves developer experience
when debugging validation errors by providing clear, formatted error messages.

Changes:
- Add __str__ method to RequestValidationError
- Add __str__ method to WebSocketRequestValidationError
- Add comprehensive tests for the new string representations

The string format shows the number of errors and lists each error on a
separate line, making it easier to read error messages during debugging
and logging.
pull/14414/head
SvDp 8 months ago
parent
commit
071a046987
Failed to extract signature
  1. 18
      fastapi/exceptions.py
  2. 65
      tests/test_validation_error_str.py

18
fastapi/exceptions.py

@ -167,9 +167,25 @@ class RequestValidationError(ValidationException):
super().__init__(errors)
self.body = body
def __str__(self) -> str:
message = f"{len(self._errors)} validation error"
if len(self._errors) > 1:
message += "s"
message += " for request:\n"
for err in self._errors:
message += f" {err}\n"
return message
class WebSocketRequestValidationError(ValidationException):
pass
def __str__(self) -> str:
message = f"{len(self._errors)} validation error"
if len(self._errors) > 1:
message += "s"
message += " for WebSocket request:\n"
for err in self._errors:
message += f" {err}\n"
return message
class ResponseValidationError(ValidationException):

65
tests/test_validation_error_str.py

@ -0,0 +1,65 @@
"""Tests for __str__ methods of validation exceptions."""
from fastapi.exceptions import (
RequestValidationError,
ResponseValidationError,
WebSocketRequestValidationError,
)
def test_request_validation_error_str_single_error():
"""Test string representation of RequestValidationError with single error."""
errors = [{"type": "int_parsing", "loc": ["query", "id"], "msg": "Input should be a valid integer"}]
exc = RequestValidationError(errors)
result = str(exc)
assert "1 validation error for request:" in result
assert "{'type': 'int_parsing'" in result
def test_request_validation_error_str_multiple_errors():
"""Test string representation of RequestValidationError with multiple errors."""
errors = [
{"type": "int_parsing", "loc": ["query", "id"], "msg": "Input should be a valid integer"},
{"type": "missing", "loc": ["query", "name"], "msg": "Field required"},
]
exc = RequestValidationError(errors)
result = str(exc)
assert "2 validation errors for request:" in result
assert "int_parsing" in result
assert "missing" in result
def test_websocket_request_validation_error_str_single_error():
"""Test string representation of WebSocketRequestValidationError with single error."""
errors = [{"type": "int_parsing", "loc": ["query", "id"], "msg": "Input should be a valid integer"}]
exc = WebSocketRequestValidationError(errors)
result = str(exc)
assert "1 validation error for WebSocket request:" in result
assert "{'type': 'int_parsing'" in result
def test_websocket_request_validation_error_str_multiple_errors():
"""Test string representation of WebSocketRequestValidationError with multiple errors."""
errors = [
{"type": "int_parsing", "loc": ["query", "id"], "msg": "Input should be a valid integer"},
{"type": "missing", "loc": ["query", "name"], "msg": "Field required"},
]
exc = WebSocketRequestValidationError(errors)
result = str(exc)
assert "2 validation errors for WebSocket request:" in result
assert "int_parsing" in result
assert "missing" in result
def test_response_validation_error_str_consistency():
"""Test that ResponseValidationError has similar __str__ behavior."""
errors = [{"type": "int_parsing", "loc": ["response", "id"], "msg": "Input should be a valid integer"}]
exc = ResponseValidationError(errors)
result = str(exc)
assert "1 validation error" in result
assert "{'type': 'int_parsing'" in result
Loading…
Cancel
Save