# ALT Error Handling
[](https://www.python.org/downloads/)
[](https://opensource.org/licenses/MIT)
[](https://github.com/psf/black)
Advanced error handling utilities for Python applications, providing decorators and context managers for consistent and robust error management.
## Features
- ๐ฏ **Consistent Error Handling**: Decorators for standardized error handling across your application
- ๐ **Exception Conversion**: Transform exceptions to match your application's error hierarchy
- ๐ **Contextual Information**: Add context to exceptions for better debugging
- ๐ก๏ธ **Safe Execution**: Execute functions with fallback values on error
- ๐งน **Cleanup Guarantees**: Ensure cleanup code runs even when errors occur
- ๐ **Error Aggregation**: Combine multiple errors into comprehensive error reports
- ๐ **Exception Chain Formatting**: Format exception chains for logging
## Installation
```bash
pip install ALT-error-handling
```
For development:
```bash
git clone https://github.com/Avilir/ALT-error-handling.git
cd ALT-error-handling
pip install -e ".[dev]"
```
## Quick Start
### Basic Error Handling
```python
from alt_error_handling import handle_errors
@handle_errors(ValueError, TypeError, reraise=False, default_return=None)
def risky_function(data):
# This function might raise ValueError or TypeError
return process_data(data)
# If an error occurs, it will be logged and None will be returned
result = risky_function(invalid_data)
```
### Adding Context to Errors
```python
from alt_error_handling import error_context
def process_user_data(user_id, data):
with error_context("processing user data", user_id=user_id, data_size=len(data)):
# Any exception here will include the context information
validate_data(data)
transform_data(data)
save_data(user_id, data)
```
## Core Features
### 1. Error Handling Decorator
The `handle_errors` decorator provides comprehensive error handling with logging:
```python
from alt_error_handling import handle_errors
import logging
# Set up logging
logger = logging.getLogger(__name__)
@handle_errors(
IOError,
OSError,
reraise=True, # Re-raise after logging
log_level=logging.ERROR,
context="file operation",
logger=logger
)
def read_config(path):
with open(path) as f:
return json.load(f)
```
### 2. Exception Conversion
Transform exceptions to match your application's error hierarchy:
```python
from alt_error_handling import convert_exceptions
class DataValidationError(Exception):
"""Application-specific validation error"""
pass
@convert_exceptions({
ValueError: DataValidationError,
TypeError: lambda e: DataValidationError(f"Invalid type: {e}"),
KeyError: lambda e: DataValidationError(f"Missing field: {e}")
})
def validate_user_input(data):
if not isinstance(data, dict):
raise TypeError("Data must be a dictionary")
if "username" not in data:
raise KeyError("username")
if not data["username"]:
raise ValueError("Username cannot be empty")
```
### 3. Safe Execution
Execute functions with fallback values:
```python
from alt_error_handling import safe_execute
# Parse JSON with fallback to empty dict
config = safe_execute(
json.loads,
config_string,
default={},
exceptions=(json.JSONDecodeError,)
)
# Calculate with fallback
result = safe_execute(
lambda: x / y,
default=float('inf'),
exceptions=(ZeroDivisionError,)
)
```
### 4. Error Context Manager
Add debugging context to any code block:
```python
from alt_error_handling import error_context, ErrorHandlingError
class DatabaseError(ErrorHandlingError):
"""Custom database error with context support"""
pass
def update_user(user_id, updates):
with error_context(
"updating user",
DatabaseError,
user_id=user_id,
update_fields=list(updates.keys())
):
user = db.get_user(user_id)
user.update(updates)
db.save(user)
```
### 5. Cleanup Guarantees
Ensure cleanup code runs even when errors occur:
```python
from alt_error_handling import ensure_cleanup
def cleanup_resources():
close_connections()
release_locks()
clean_temp_files()
@ensure_cleanup(cleanup_resources)
def process_with_resources():
acquire_locks()
open_connections()
# If this fails, cleanup_resources will still run
do_processing()
```
### 6. Error Aggregation
Collect multiple errors for comprehensive error reporting:
```python
from alt_error_handling import aggregate_errors
errors = []
for item in items:
try:
process_item(item)
except Exception as e:
errors.append(e)
if errors:
# Combine all errors into one comprehensive error
raise aggregate_errors(
errors,
message="Failed to process items",
exception_type=ProcessingError
)
```
### 7. Exception Chain Formatting
Format exception chains for logging:
```python
from alt_error_handling import format_exception_chain
try:
risky_operation()
except Exception as e:
# Get a formatted string of the exception chain
error_details = format_exception_chain(e, include_traceback=True)
logger.error(f"Operation failed:\n{error_details}")
```
## Best Practices
### 1. Consistent Error Handling Strategy
```python
# Define application-specific errors
class AppError(ErrorHandlingError):
"""Base application error"""
pass
class ValidationError(AppError):
"""Validation error"""
pass
class ProcessingError(AppError):
"""Processing error"""
pass
# Use consistent error handling throughout
@handle_errors(Exception, reraise=True, context="data processing")
@convert_exceptions({
ValueError: ValidationError,
TypeError: ValidationError,
RuntimeError: ProcessingError
})
def process_data(data):
validate(data)
return transform(data)
```
### 2. Layered Error Handling
```python
# Low-level function with specific error handling
@handle_errors(IOError, OSError, reraise=False, default_return=None)
def read_file(path):
with open(path) as f:
return f.read()
# High-level function with broader error handling
@handle_errors(Exception, context="processing pipeline")
def process_files(file_paths):
results = []
for path in file_paths:
with error_context("processing file", path=path):
data = read_file(path)
if data:
results.append(transform_data(data))
return results
```
### 3. Detailed Error Context
```python
@handle_errors(Exception, reraise=True)
def complex_operation(user_id, data, options):
with error_context(
"complex operation",
user_id=user_id,
data_size=len(data),
options=options,
timestamp=datetime.now().isoformat()
):
# Multiple steps with individual context
with error_context("validation step"):
validate_input(data, options)
with error_context("processing step"):
result = process(data)
with error_context("save step"):
save_result(user_id, result)
return result
```
## Advanced Usage
### Custom Logging Function
```python
def custom_error_logger(logger, error, context, details):
# Send to monitoring service
monitoring.send_error({
'error_type': type(error).__name__,
'error_message': str(error),
'context': context,
'function': details['function'],
'timestamp': datetime.now().isoformat()
})
# Log locally
logger.error(f"{context} failed: {error}")
@handle_errors(
Exception,
log_func=custom_error_logger,
context="critical operation"
)
def critical_operation():
# ...
```
### Conditional Error Handling
```python
def make_error_handler(debug_mode=False):
return handle_errors(
Exception,
reraise=debug_mode, # Reraise in debug mode
default_return=None if not debug_mode else ...,
log_level=logging.DEBUG if debug_mode else logging.ERROR
)
# Use based on configuration
@make_error_handler(debug_mode=app.config.DEBUG)
def application_function():
# ...
```
## Testing
The library includes comprehensive tests. Run them with:
```bash
# Run all tests
pytest
# Run with coverage
pytest --cov=alt_error_handling
# Run specific test file
pytest tests/test_core.py
```
## Development
### Setup Development Environment
```bash
# Clone the repository
git clone https://github.com/Avilir/ALT-error-handling.git
cd ALT-error-handling
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install in development mode
pip install -e ".[dev]"
# Install pre-commit hooks
pre-commit install
```
### Running Quality Checks
```bash
# Type checking
mypy src
# Linting
ruff check .
# Formatting
black .
# All checks
make check # If Makefile is available
```
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Author
**Avi Layani**
Email: alayani@redhat.com
## Acknowledgments
- Inspired by error handling patterns in various Python frameworks
- Built with modern Python development best practices
- Type hints for better IDE support and code clarity
Raw data
{
"_id": null,
"home_page": null,
"name": "ALT-error-handling",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": "Avi Layani <alayani@redhat.com>",
"keywords": "error, exception, handling, utilities, decorators, logging",
"author": null,
"author_email": "Avi Layani <alayani@redhat.com>",
"download_url": "https://files.pythonhosted.org/packages/67/01/4423bb012972b9c6d8ee20918cdd90da0e58a0d47bace91fa787001579f7/alt_error_handling-0.1.0.tar.gz",
"platform": null,
"description": "# ALT Error Handling\n\n[](https://www.python.org/downloads/)\n[](https://opensource.org/licenses/MIT)\n[](https://github.com/psf/black)\n\nAdvanced error handling utilities for Python applications, providing decorators and context managers for consistent and robust error management.\n\n## Features\n\n- \ud83c\udfaf **Consistent Error Handling**: Decorators for standardized error handling across your application\n- \ud83d\udd04 **Exception Conversion**: Transform exceptions to match your application's error hierarchy\n- \ud83d\udcdd **Contextual Information**: Add context to exceptions for better debugging\n- \ud83d\udee1\ufe0f **Safe Execution**: Execute functions with fallback values on error\n- \ud83e\uddf9 **Cleanup Guarantees**: Ensure cleanup code runs even when errors occur\n- \ud83d\udcca **Error Aggregation**: Combine multiple errors into comprehensive error reports\n- \ud83d\udd17 **Exception Chain Formatting**: Format exception chains for logging\n\n## Installation\n\n```bash\npip install ALT-error-handling\n```\n\nFor development:\n```bash\ngit clone https://github.com/Avilir/ALT-error-handling.git\ncd ALT-error-handling\npip install -e \".[dev]\"\n```\n\n## Quick Start\n\n### Basic Error Handling\n\n```python\nfrom alt_error_handling import handle_errors\n\n@handle_errors(ValueError, TypeError, reraise=False, default_return=None)\ndef risky_function(data):\n # This function might raise ValueError or TypeError\n return process_data(data)\n\n# If an error occurs, it will be logged and None will be returned\nresult = risky_function(invalid_data)\n```\n\n### Adding Context to Errors\n\n```python\nfrom alt_error_handling import error_context\n\ndef process_user_data(user_id, data):\n with error_context(\"processing user data\", user_id=user_id, data_size=len(data)):\n # Any exception here will include the context information\n validate_data(data)\n transform_data(data)\n save_data(user_id, data)\n```\n\n## Core Features\n\n### 1. Error Handling Decorator\n\nThe `handle_errors` decorator provides comprehensive error handling with logging:\n\n```python\nfrom alt_error_handling import handle_errors\nimport logging\n\n# Set up logging\nlogger = logging.getLogger(__name__)\n\n@handle_errors(\n IOError, \n OSError,\n reraise=True, # Re-raise after logging\n log_level=logging.ERROR,\n context=\"file operation\",\n logger=logger\n)\ndef read_config(path):\n with open(path) as f:\n return json.load(f)\n```\n\n### 2. Exception Conversion\n\nTransform exceptions to match your application's error hierarchy:\n\n```python\nfrom alt_error_handling import convert_exceptions\n\nclass DataValidationError(Exception):\n \"\"\"Application-specific validation error\"\"\"\n pass\n\n@convert_exceptions({\n ValueError: DataValidationError,\n TypeError: lambda e: DataValidationError(f\"Invalid type: {e}\"),\n KeyError: lambda e: DataValidationError(f\"Missing field: {e}\")\n})\ndef validate_user_input(data):\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dictionary\")\n if \"username\" not in data:\n raise KeyError(\"username\")\n if not data[\"username\"]:\n raise ValueError(\"Username cannot be empty\")\n```\n\n### 3. Safe Execution\n\nExecute functions with fallback values:\n\n```python\nfrom alt_error_handling import safe_execute\n\n# Parse JSON with fallback to empty dict\nconfig = safe_execute(\n json.loads, \n config_string, \n default={},\n exceptions=(json.JSONDecodeError,)\n)\n\n# Calculate with fallback\nresult = safe_execute(\n lambda: x / y,\n default=float('inf'),\n exceptions=(ZeroDivisionError,)\n)\n```\n\n### 4. Error Context Manager\n\nAdd debugging context to any code block:\n\n```python\nfrom alt_error_handling import error_context, ErrorHandlingError\n\nclass DatabaseError(ErrorHandlingError):\n \"\"\"Custom database error with context support\"\"\"\n pass\n\ndef update_user(user_id, updates):\n with error_context(\n \"updating user\",\n DatabaseError,\n user_id=user_id,\n update_fields=list(updates.keys())\n ):\n user = db.get_user(user_id)\n user.update(updates)\n db.save(user)\n```\n\n### 5. Cleanup Guarantees\n\nEnsure cleanup code runs even when errors occur:\n\n```python\nfrom alt_error_handling import ensure_cleanup\n\ndef cleanup_resources():\n close_connections()\n release_locks()\n clean_temp_files()\n\n@ensure_cleanup(cleanup_resources)\ndef process_with_resources():\n acquire_locks()\n open_connections()\n # If this fails, cleanup_resources will still run\n do_processing()\n```\n\n### 6. Error Aggregation\n\nCollect multiple errors for comprehensive error reporting:\n\n```python\nfrom alt_error_handling import aggregate_errors\n\nerrors = []\nfor item in items:\n try:\n process_item(item)\n except Exception as e:\n errors.append(e)\n\nif errors:\n # Combine all errors into one comprehensive error\n raise aggregate_errors(\n errors,\n message=\"Failed to process items\",\n exception_type=ProcessingError\n )\n```\n\n### 7. Exception Chain Formatting\n\nFormat exception chains for logging:\n\n```python\nfrom alt_error_handling import format_exception_chain\n\ntry:\n risky_operation()\nexcept Exception as e:\n # Get a formatted string of the exception chain\n error_details = format_exception_chain(e, include_traceback=True)\n logger.error(f\"Operation failed:\\n{error_details}\")\n```\n\n## Best Practices\n\n### 1. Consistent Error Handling Strategy\n\n```python\n# Define application-specific errors\nclass AppError(ErrorHandlingError):\n \"\"\"Base application error\"\"\"\n pass\n\nclass ValidationError(AppError):\n \"\"\"Validation error\"\"\"\n pass\n\nclass ProcessingError(AppError):\n \"\"\"Processing error\"\"\"\n pass\n\n# Use consistent error handling throughout\n@handle_errors(Exception, reraise=True, context=\"data processing\")\n@convert_exceptions({\n ValueError: ValidationError,\n TypeError: ValidationError,\n RuntimeError: ProcessingError\n})\ndef process_data(data):\n validate(data)\n return transform(data)\n```\n\n### 2. Layered Error Handling\n\n```python\n# Low-level function with specific error handling\n@handle_errors(IOError, OSError, reraise=False, default_return=None)\ndef read_file(path):\n with open(path) as f:\n return f.read()\n\n# High-level function with broader error handling\n@handle_errors(Exception, context=\"processing pipeline\")\ndef process_files(file_paths):\n results = []\n for path in file_paths:\n with error_context(\"processing file\", path=path):\n data = read_file(path)\n if data:\n results.append(transform_data(data))\n return results\n```\n\n### 3. Detailed Error Context\n\n```python\n@handle_errors(Exception, reraise=True)\ndef complex_operation(user_id, data, options):\n with error_context(\n \"complex operation\",\n user_id=user_id,\n data_size=len(data),\n options=options,\n timestamp=datetime.now().isoformat()\n ):\n # Multiple steps with individual context\n with error_context(\"validation step\"):\n validate_input(data, options)\n \n with error_context(\"processing step\"):\n result = process(data)\n \n with error_context(\"save step\"):\n save_result(user_id, result)\n \n return result\n```\n\n## Advanced Usage\n\n### Custom Logging Function\n\n```python\ndef custom_error_logger(logger, error, context, details):\n # Send to monitoring service\n monitoring.send_error({\n 'error_type': type(error).__name__,\n 'error_message': str(error),\n 'context': context,\n 'function': details['function'],\n 'timestamp': datetime.now().isoformat()\n })\n \n # Log locally\n logger.error(f\"{context} failed: {error}\")\n\n@handle_errors(\n Exception,\n log_func=custom_error_logger,\n context=\"critical operation\"\n)\ndef critical_operation():\n # ...\n```\n\n### Conditional Error Handling\n\n```python\ndef make_error_handler(debug_mode=False):\n return handle_errors(\n Exception,\n reraise=debug_mode, # Reraise in debug mode\n default_return=None if not debug_mode else ...,\n log_level=logging.DEBUG if debug_mode else logging.ERROR\n )\n\n# Use based on configuration\n@make_error_handler(debug_mode=app.config.DEBUG)\ndef application_function():\n # ...\n```\n\n## Testing\n\nThe library includes comprehensive tests. Run them with:\n\n```bash\n# Run all tests\npytest\n\n# Run with coverage\npytest --cov=alt_error_handling\n\n# Run specific test file\npytest tests/test_core.py\n```\n\n## Development\n\n### Setup Development Environment\n\n```bash\n# Clone the repository\ngit clone https://github.com/Avilir/ALT-error-handling.git\ncd ALT-error-handling\n\n# Create virtual environment\npython -m venv venv\nsource venv/bin/activate # On Windows: venv\\Scripts\\activate\n\n# Install in development mode\npip install -e \".[dev]\"\n\n# Install pre-commit hooks\npre-commit install\n```\n\n### Running Quality Checks\n\n```bash\n# Type checking\nmypy src\n\n# Linting\nruff check .\n\n# Formatting\nblack .\n\n# All checks\nmake check # If Makefile is available\n```\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/AmazingFeature`)\n3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)\n4. Push to the branch (`git push origin feature/AmazingFeature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Author\n\n**Avi Layani** \nEmail: alayani@redhat.com\n\n## Acknowledgments\n\n- Inspired by error handling patterns in various Python frameworks\n- Built with modern Python development best practices\n- Type hints for better IDE support and code clarity\n",
"bugtrack_url": null,
"license": null,
"summary": "Advanced error handling utilities for Python applications",
"version": "0.1.0",
"project_urls": {
"Bug Tracker": "https://github.com/Avilir/ALT-error-handling/issues",
"Homepage": "https://github.com/Avilir/ALT-error-handling",
"Repository": "https://github.com/Avilir/ALT-error-handling"
},
"split_keywords": [
"error",
" exception",
" handling",
" utilities",
" decorators",
" logging"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "5a8ff7392febc7db4961185511a028008c94de4c5ea9fd2308dbaeaef4488303",
"md5": "8fba663bbdad5486a96a09002002807d",
"sha256": "fb989d2115d2bca7cc4c64af15208063612245f0f02bfd0a60f4cebee0c69f32"
},
"downloads": -1,
"filename": "alt_error_handling-0.1.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "8fba663bbdad5486a96a09002002807d",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 9926,
"upload_time": "2025-09-06T12:20:03",
"upload_time_iso_8601": "2025-09-06T12:20:03.893027Z",
"url": "https://files.pythonhosted.org/packages/5a/8f/f7392febc7db4961185511a028008c94de4c5ea9fd2308dbaeaef4488303/alt_error_handling-0.1.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "67014423bb012972b9c6d8ee20918cdd90da0e58a0d47bace91fa787001579f7",
"md5": "8c619d87ce1714a1695e63e49ba47c1e",
"sha256": "6d3f43e26d952a0e949d580c528a8f73f2d3c88569455870082b60b59afb8332"
},
"downloads": -1,
"filename": "alt_error_handling-0.1.0.tar.gz",
"has_sig": false,
"md5_digest": "8c619d87ce1714a1695e63e49ba47c1e",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 13506,
"upload_time": "2025-09-06T12:20:05",
"upload_time_iso_8601": "2025-09-06T12:20:05.228956Z",
"url": "https://files.pythonhosted.org/packages/67/01/4423bb012972b9c6d8ee20918cdd90da0e58a0d47bace91fa787001579f7/alt_error_handling-0.1.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-09-06 12:20:05",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "Avilir",
"github_project": "ALT-error-handling",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "alt-error-handling"
}