Metadata-Version: 2.4
Name: python-custom-exceptions
Version: 1.0.0
Summary: A collection of custom exceptions for Python projects.
Author: Avi Zaguri
License: MIT
Project-URL: Homepage, https://github.com/aviz92/python-custom-exceptions
Project-URL: Repository, https://github.com/aviz92/python-custom-exceptions
Project-URL: Issues, https://github.com/aviz92/python-custom-exceptions/issues
Keywords: development,python,exceptions,error-handling
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: python-base-toolkit>=1.1.3
Dynamic: license-file

# Python Custom Exceptions
A collection of structured, ready-to-use exception classes for Python projects. <br>
Every exception renders as JSON with its type, a human-readable message, and optional diagnostic info,
so errors are easy to read in logs and easy to parse by tools. <br>

---

### Features
- ✅ Specific Exception Classes: Ready-made exceptions for common error scenarios.
- ✅ Structured Output: `str(exception)` is a JSON document with type, message and diagnostic info.
- ✅ Diagnostic Info: Attach typed context (`TypedDict`, `dict` or dataclass) to any exception.
- ✅ Single Base Class: Everything inherits from `BaseCustomException`, so one `except` catches them all.
- ✅ Easy Extension: Subclass `BaseCustomException` to add your own exceptions.

---

### Installation
```bash
uv add python-custom-exceptions
```
or with pip:
```bash
pip install python-custom-exceptions
```
Requires Python 3.12+.

---

### Available Exceptions
| Exception | Arguments | Message |
|-----------|-----------|---------|
| `BaseCustomException` | `message_with_marking_dynamic_variables` | `<message>` |
| `ComparisonException` | `expected_value`, `actual_value`, `subject=None` | `Expected <subject> to be [<expected>], but got [<actual>]` |
| `ConnectionException` | `host`, `message=None` | `Connection failed: Unable to establish a connection to the remote host ["<host>"]. ...` |
| `IsExistException` | `subject` | `[<subject>] is exists` |
| `IsNotExistException` | `subject` | `[<subject>] is not exists` |
| `IsExistAfterOperationException` | `subject`, `operation` | `<subject> exists after trying to <operation>` |
| `IsNotExistAfterOperationException` | `subject`, `operation` | `<subject> does not exist after trying to <operation>` |
| `OperationException` | `operation` | `Operation <operation> failed` |
| `NotOperationalException` | `subject` | `<subject> is not Operational` |
| `UnexpectedlySucceededOperationException` | `operation` | `Operation <operation> unexpectedly succeeded` |
| `TimedExecutionException` | `operation`, `timeout` | `Operation <operation> did not succeed within [<timeout>] seconds` |
| `UnsupportedExceptions` | `unsupported_subject` | `<unsupported_subject> is unsupported` |
| `UnsupportedOSExceptions` | `os_name` | `Unsupported OS: ["<os_name>"]` |
| `WrongUsageException` | `message` | `Wrong usage: <message>` |

All exceptions also accept an optional `diagnostic_info` argument.

---

### Usage Examples

#### Raise an exception with diagnostic info
```python
from pathlib import Path

from python_custom_exceptions import DiagnosticInfo, IsNotExistException


class PathDiagnosticInfo(DiagnosticInfo):
    path: str


path = Path("/tmp/missing")
if not path.exists():
    raise IsNotExistException(
        subject="Directory",
        diagnostic_info=PathDiagnosticInfo(path=str(path)),
    )
```
Output:
```json
{
    "exception_type": "IsNotExistException",
    "message": "[Directory] is not exists",
    "diagnostic_info": {
        "path": "/tmp/missing"
    }
}
```

#### Catch any custom exception
```python
from python_custom_exceptions import BaseCustomException, ComparisonException

try:
    raise ComparisonException(expected_value=200, actual_value=500, subject="status code")
except BaseCustomException as exc:
    print(exc.exception_type)   # ComparisonException
    print(exc.message)          # Expected status code to be [200], but got [500]
    print(exc.diagnostic_info)  # {}
```

#### Define your own exception
```python
from python_custom_exceptions import BaseCustomException, DiagnosticInfo


class QuotaExceededException(BaseCustomException):
    def __init__(self, resource: str, limit: int, diagnostic_info: dict | DiagnosticInfo | None = None) -> None:
        super().__init__(
            message_with_marking_dynamic_variables=f"Quota for [{resource}] exceeded the limit of [{limit}]",
            diagnostic_info=diagnostic_info,
        )
```

---

### Development
```bash
git clone https://github.com/aviz92/python-custom-exceptions.git
cd python-custom-exceptions
uv sync                    # create .venv and install runtime + dev dependencies
uv run pre-commit install  # enable git hooks
uv run pytest              # run the tests
uv build                   # build sdist + wheel into dist/
```

---

### 🤝 Contributing
If you have a helpful exception, pattern, or improvement to suggest:
1. Fork the repo
2. Create a new branch
3. Submit a pull request

I welcome additions that promote clean, productive, and maintainable development. <br>

---

### 🙏 Thanks
Thanks for exploring this repository! <br>
Happy coding! <br>
