From 071a046987037c4c5545a62e15fab39c5775741c Mon Sep 17 00:00:00 2001 From: SvDp Date: Fri, 28 Nov 2025 16:24:12 +0530 Subject: [PATCH] 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. --- fastapi/exceptions.py | 18 ++++++++- tests/test_validation_error_str.py | 65 ++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 tests/test_validation_error_str.py diff --git a/fastapi/exceptions.py b/fastapi/exceptions.py index 0620428be..10549b33c 100644 --- a/fastapi/exceptions.py +++ b/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): diff --git a/tests/test_validation_error_str.py b/tests/test_validation_error_str.py new file mode 100644 index 000000000..26f5d6447 --- /dev/null +++ b/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