Skip to content

Commit 1ca9b75

Browse files
update changelog, refactor format_validation_errors
1 parent ed7fa8c commit 1ca9b75

3 files changed

Lines changed: 151 additions & 72 deletions

File tree

archipy/helpers/utils/base_utils.py

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import re
22

3-
from pydantic import ValidationError
4-
53
from archipy.helpers.utils.datetime_utils import DatetimeUtils
64
from archipy.helpers.utils.error_utils import ErrorUtils
75
from archipy.helpers.utils.file_utils import FileUtils
@@ -22,32 +20,6 @@ class BaseUtils(ErrorUtils, DatetimeUtils, PasswordUtils, JWTUtils, TOTPUtils, F
2220
This class inherits from various utility classes to provide a centralized place for common utility methods.
2321
"""
2422

25-
@staticmethod
26-
def format_validation_errors(
27-
validation_error: ValidationError, *, include_type: bool = False
28-
) -> list[dict[str, str]]:
29-
"""Formats Pydantic validation errors into a structured format.
30-
31-
Args:
32-
validation_error (ValidationError): The validation error to format.
33-
include_type (bool): Whether to include the error type in the output. Defaults to False.
34-
35-
Returns:
36-
list[dict[str, str]]: A list of formatted validation error details.
37-
"""
38-
formatted_errors = []
39-
for error in validation_error.errors():
40-
error_dict = {
41-
"field": ".".join(str(x) for x in error["loc"]),
42-
"message": error["msg"],
43-
"value": str(error.get("input", "")),
44-
}
45-
if include_type:
46-
error_dict["type"] = error["type"]
47-
formatted_errors.append(error_dict)
48-
49-
return formatted_errors
50-
5123
@staticmethod
5224
def sanitize_iranian_landline_or_phone_number(landline_or_phone_number: str) -> str:
5325
"""Sanitizes an Iranian landline or mobile phone number by removing non-numeric characters and standardizing the format.

archipy/helpers/utils/error_utils.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import logging
22
from typing import Any, Protocol
33

4+
from pydantic_core._pydantic_core import ValidationError
5+
46
from archipy.configs.base_config import BaseConfig
57
from archipy.models.dtos.fastapi_exception_response_dto import (
68
FastAPIErrorResponseDTO,
@@ -55,6 +57,34 @@ class UNKNOWN:
5557
class ErrorUtils:
5658
"""A utility class for handling errors, including capturing, reporting, and generating responses."""
5759

60+
@staticmethod
61+
def format_validation_errors(
62+
validation_error: ValidationError,
63+
*,
64+
include_type: bool = False,
65+
) -> list[dict[str, str]]:
66+
"""Formats Pydantic validation errors into a structured format.
67+
68+
Args:
69+
validation_error (ValidationError): The validation error to format.
70+
include_type (bool): Whether to include the error type in the output. Defaults to False.
71+
72+
Returns:
73+
list[dict[str, str]]: A list of formatted validation error details.
74+
"""
75+
formatted_errors = []
76+
for error in validation_error.errors():
77+
error_dict = {
78+
"field": ".".join(str(x) for x in error["loc"]),
79+
"message": error["msg"],
80+
"value": str(error.get("input", "")),
81+
}
82+
if include_type:
83+
error_dict["type"] = error["type"]
84+
formatted_errors.append(error_dict)
85+
86+
return formatted_errors
87+
5888
@staticmethod
5989
def capture_exception(exception: BaseException) -> None:
6090
"""Captures an exception and reports it to configured external services.

docs/changelog.md

Lines changed: 121 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,112 +2,189 @@
22

33
All notable changes to ArchiPy are documented in this changelog, organized by version.
44

5+
## [3.6.0] - 2025-07-29
6+
7+
### New Features
8+
9+
#### gRPC Exception Interceptor System
10+
11+
- **Centralized Exception Handling** - Implemented comprehensive gRPC server exception interceptors for both synchronous
12+
and asynchronous operations
13+
- Added `GrpcServerExceptionInterceptor` for synchronous gRPC services with automatic exception conversion
14+
- Added `AsyncGrpcServerExceptionInterceptor` for asynchronous gRPC services with async exception handling
15+
- Eliminated the need for repetitive try-catch blocks in individual gRPC service methods
16+
- Automatic conversion of exceptions to appropriate gRPC error responses with proper status codes
17+
18+
#### Enhanced Error Handling
19+
20+
- **Pydantic Validation Error Handling** - Integrated automatic Pydantic validation error processing in gRPC
21+
interceptors
22+
- Automatic conversion of ValidationError to InvalidArgumentError with detailed error information
23+
- Structured validation error formatting with field-level error details
24+
- Enhanced debugging capabilities with comprehensive validation error reporting
25+
26+
#### Language Configuration System
27+
28+
- **Global Language Configuration** - Added LANGUAGE configuration to BaseConfig for consistent language handling
29+
- Introduced LANGUAGE attribute in BaseConfig with default Persian (FA) language support
30+
- Standardized language type constants to uppercase for ISO compliance
31+
- Improved language handling across error messages and user interfaces
32+
33+
### Improvements
34+
35+
#### gRPC Status Code Management
36+
37+
- **Enhanced Status Code Handling** - Improved gRPC status code conversion and management in BaseError
38+
- Added static method for converting integer status codes to gRPC StatusCode enums
39+
- Enhanced metadata handling in gRPC abort methods with conditional additional data inclusion
40+
- Refined type hints for context parameters in abort methods for better clarity
41+
- Improved error context preservation and debugging capabilities
42+
43+
#### Error System Refactoring
44+
45+
- **Optional Language Parameters** - Refactored error handling classes to use optional language parameters
46+
- Removed mandatory language parameter requirements for improved flexibility
47+
- Enhanced error initialization with automatic language detection from global configuration
48+
- Improved error message consistency and localization support
49+
- Maintained backward compatibility while improving developer experience
50+
51+
### Bug Fixes
52+
53+
#### Error Initialization
54+
55+
- **Language Configuration Fix** - Fixed language initialization in BaseError to use global configuration
56+
- Ensured language is set correctly from global configuration when not provided during initialization
57+
- Improved error message consistency across different initialization scenarios
58+
- Enhanced code readability and maintainability
59+
60+
#### Type Safety Improvements
61+
62+
- **Enhanced Type Hints** - Improved type hints for gRPC status codes and error handling
63+
- Refined type annotations for better IDE support and code reliability
64+
- Enhanced type safety across error handling components
65+
- Improved developer experience with better autocomplete and error detection
66+
67+
### Code Quality
68+
69+
- **Comprehensive Error Coverage** - Updated all error classes to support the new language and gRPC handling system
70+
- Enhanced auth_errors, business_errors, database_errors, network_errors, resource_errors, system_errors, and
71+
validation_errors
72+
- Improved error categorization and handling consistency
73+
- Enhanced error reporting and debugging capabilities across all error types
74+
575
## [3.5.2] - 2025-07-28
676

777
### Bug Fixes
878

979
#### Elasticsearch Authentication
1080

11-
- **Password Secret Value Extraction** - Fixed critical authentication issue in Elasticsearch adapters where password secret values were not being properly extracted
12-
- Updated both synchronous and asynchronous Elasticsearch adapters to use `get_secret_value()` method for HTTP_PASSWORD
13-
- Resolved authentication failures when using SecretStr password configuration
14-
- Improved security by properly handling encrypted password fields in Elasticsearch configuration
81+
- **Password Secret Value Extraction** - Fixed critical authentication issue in Elasticsearch adapters where password
82+
secret values were not being properly extracted
83+
- Updated both synchronous and asynchronous Elasticsearch adapters to use `get_secret_value()` method for
84+
HTTP_PASSWORD
85+
- Resolved authentication failures when using SecretStr password configuration
86+
- Improved security by properly handling encrypted password fields in Elasticsearch configuration
1587

1688
### Dependencies
1789

1890
- **Poetry Lock Update** - Updated poetry.lock file to Poetry 2.1.2 for improved dependency management
19-
- Enhanced dependency resolution with latest Poetry version
20-
- Updated platform-specific package markers for better cross-platform compatibility
21-
- Improved package hash verification and security
91+
- Enhanced dependency resolution with latest Poetry version
92+
- Updated platform-specific package markers for better cross-platform compatibility
93+
- Improved package hash verification and security
2294

2395
### Code Quality
2496

2597
- **Authentication Consistency** - Standardized password handling across Elasticsearch adapters
26-
- Ensured consistent secret value extraction in both sync and async adapters
27-
- Maintained backward compatibility while improving security practices
28-
- Enhanced error handling for authentication configuration
98+
- Ensured consistent secret value extraction in both sync and async adapters
99+
- Maintained backward compatibility while improving security practices
100+
- Enhanced error handling for authentication configuration
29101

30102
## [3.5.1] - 2025-07-28
31103

32104
### Bug Fixes
33105

34106
#### HTTP Status Code Handling
35107

36-
- **Status Code Name Mismatch** - Fixed critical issue in FastAPIExceptionHandler where `http_status_code` was incorrectly referenced
37-
- Changed from `exception.http_status_code` to `exception.http_status_code_value` for proper status code retrieval
38-
- Resolved HTTP status code name mismatch that was causing incorrect error responses
39-
- Improved error handling consistency in FastAPI exception processing
108+
- **Status Code Name Mismatch** - Fixed critical issue in FastAPIExceptionHandler where `http_status_code` was
109+
incorrectly referenced
110+
- Changed from `exception.http_status_code` to `exception.http_status_code_value` for proper status code retrieval
111+
- Resolved HTTP status code name mismatch that was causing incorrect error responses
112+
- Improved error handling consistency in FastAPI exception processing
40113

41114
### Improvements
42115

43116
#### Protobuf DTO Runtime Type Safety
44117

45118
- **Runtime Type Checking** - Enhanced BaseProtobufDTO with comprehensive runtime type validation
46-
- Added runtime type checking in `from_proto()` method to validate input parameter types
47-
- Implemented proper type validation before protobuf message processing
48-
- Enhanced error messages with clear type mismatch information
119+
- Added runtime type checking in `from_proto()` method to validate input parameter types
120+
- Implemented proper type validation before protobuf message processing
121+
- Enhanced error messages with clear type mismatch information
49122

50123
#### Custom Exception Integration
51124

52125
- **Custom Exception Handling** - Replaced generic TypeError with domain-specific InvalidEntityTypeError
53-
- Updated protobuf DTO type validation to use `InvalidEntityTypeError` for better error categorization
54-
- Improved error context with expected and actual type information
55-
- Enhanced error handling consistency across the protobuf DTO system
126+
- Updated protobuf DTO type validation to use `InvalidEntityTypeError` for better error categorization
127+
- Improved error context with expected and actual type information
128+
- Enhanced error handling consistency across the protobuf DTO system
56129

57130
### Code Quality Enhancements
58131

59132
- **Error Handling Consistency** - Standardized error handling patterns across protobuf DTO operations
60-
- Improved error message clarity and debugging capabilities
61-
- Enhanced type safety with proper exception chaining
62-
- Maintained backward compatibility while improving error reporting
133+
- Improved error message clarity and debugging capabilities
134+
- Enhanced type safety with proper exception chaining
135+
- Maintained backward compatibility while improving error reporting
63136

64137
## [3.5.0] - 2025-07-26
65138

66139
### New Features
67140

68141
#### Protobuf DTO Support
69142

70-
- **BaseProtobufDTO** - Added new base class for Data Transfer Objects that can be converted to and from Protobuf messages
71-
- Provides seamless integration between Pydantic DTOs and Google Protocol Buffers
72-
- Supports bidirectional conversion with `from_proto()` and `to_proto()` methods
73-
- Includes runtime dependency checking for protobuf availability
74-
- Maintains type safety with proper error handling for missing protobuf dependencies
143+
- **BaseProtobufDTO** - Added new base class for Data Transfer Objects that can be converted to and from Protobuf
144+
messages
145+
- Provides seamless integration between Pydantic DTOs and Google Protocol Buffers
146+
- Supports bidirectional conversion with `from_proto()` and `to_proto()` methods
147+
- Includes runtime dependency checking for protobuf availability
148+
- Maintains type safety with proper error handling for missing protobuf dependencies
75149

76150
### Bug Fixes
77151

78152
#### Type Safety Improvements
79153

80-
- **ClassVar Type Variable Issue** - Fixed critical type annotation issue in BaseProtobufDTO where ClassVar contained type variables
81-
- Resolved `ClassVar` parameter cannot include type variables error
82-
- Updated type annotations to use concrete `Message` type instead of type variables
83-
- Improved type safety by using proper concrete types for class variables
84-
- Added comprehensive type annotations for all methods and parameters
154+
- **ClassVar Type Variable Issue** - Fixed critical type annotation issue in BaseProtobufDTO where ClassVar contained
155+
type variables
156+
- Resolved `ClassVar` parameter cannot include type variables error
157+
- Updated type annotations to use concrete `Message` type instead of type variables
158+
- Improved type safety by using proper concrete types for class variables
159+
- Added comprehensive type annotations for all methods and parameters
85160

86161
#### Code Quality Enhancements
87162

88163
- **Import Cleanup** - Removed invalid Unicode characters and simplified import structure
89-
- Fixed invisible Unicode character `\uab` that was causing linter errors
90-
- Streamlined protobuf import logic by removing unnecessary type variables
91-
- Enhanced code readability and maintainability
92-
- Added proper docstring formatting with Google-style documentation
164+
- Fixed invisible Unicode character `\uab` that was causing linter errors
165+
- Streamlined protobuf import logic by removing unnecessary type variables
166+
- Enhanced code readability and maintainability
167+
- Added proper docstring formatting with Google-style documentation
93168

94169
#### Linting Configuration
95170

96171
- **Ruff Configuration** - Updated linting rules to accommodate protobuf DTO patterns
97-
- Added `ANN401` exception for `base_protobuf_dto.py` to allow `Any` types in `*args` and `**kwargs`
98-
- Maintained strict type checking while allowing necessary flexibility for DTO inheritance patterns
99-
- Ensured all pre-commit hooks pass without compromising code quality standards
172+
- Added `ANN401` exception for `base_protobuf_dto.py` to allow `Any` types in `*args` and `**kwargs`
173+
- Maintained strict type checking while allowing necessary flexibility for DTO inheritance patterns
174+
- Ensured all pre-commit hooks pass without compromising code quality standards
100175

101176
## [3.4.5] - 2025-07-24
102177

103178
### Improvements
104179

105180
#### Configuration Template Enhancements
106181

107-
- **Improved Readability** - Enhanced ElasticsearchAPMConfig size fields to use human-readable string values instead of raw bytes
108-
- Changed `API_REQUEST_SIZE` from `768 * 1024` to `"768kb"` for better configuration clarity
109-
- Changed `LOG_FILE_SIZE` from `50 * 1024 * 1024` to `"50mb"` for improved readability
110-
- **Configuration Clarity** - Updated size-related configuration fields to use standard size notation (kb, mb) making configuration files more intuitive and easier to understand
182+
- **Improved Readability** - Enhanced ElasticsearchAPMConfig size fields to use human-readable string values instead of
183+
raw bytes
184+
- Changed `API_REQUEST_SIZE` from `768 * 1024` to `"768kb"` for better configuration clarity
185+
- Changed `LOG_FILE_SIZE` from `50 * 1024 * 1024` to `"50mb"` for improved readability
186+
- **Configuration Clarity** - Updated size-related configuration fields to use standard size notation (kb, mb) making
187+
configuration files more intuitive and easier to understand
111188

112189
### Bug Fixes
113190

0 commit comments

Comments
 (0)