Metadata-Version: 2.4
Name: vcti-error
Version: 2.0.2
Summary: Shared exception classes for vcti packages, plus exception-to-exit-code contracts: the mechanics and the VCollab vocabularies
Author: Visual Collaboration Technologies Inc.
License-Expression: LicenseRef-Proprietary
Project-URL: Repository, https://github.com/vcollab/vcti-python-error
Project-URL: Changelog, https://github.com/vcollab/vcti-python-error/blob/main/CHANGELOG.md
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: <3.15,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Provides-Extra: lint
Requires-Dist: ruff; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: mypy; extra == "typecheck"
Dynamic: license-file

# vcti-error

Shared exception classes for vcti packages, plus exception-to-exit-code
contracts: the mechanics and the VCollab vocabularies.

## Overview

`vcti-error` provides two features, usable together or separately.
**Shared exception classes** (`vcti.error.errors`) are a common set of
exception types, such as `ConfigError` and `LicenseError`, so an error
raised in one vcti package can be caught by the same class in another.
**Exit-code contracts** decide which exit code a program returns for
the exception that ended it, so a caller that runs the program as a
subprocess can tell from the exit code what went wrong. A contract is a
mapping from exception classes to exit codes: `vcti.error.contract`
provides ready-made VCollab contracts, and `vcti.error.mechanics`
provides the functions that check, combine and apply any contract,
including your own.

## Installation

```bash
pip install vcti-error
```

### In `requirements.txt`

```
vcti-error>=2.0.2
```

### In `pyproject.toml` dependencies

```toml
dependencies = [
    "vcti-error>=2.0.2",
]
```

---

## Quick Start

### Shared exception classes

Raise a shared class where the failure happens; catch it by the same
class anywhere:

```python
from vcti.error.errors import ConfigError


def load(config: dict[str, str]) -> None:
    if "output_dir" not in config:
        raise ConfigError("missing required key 'output_dir'")


try:
    load({})
except ConfigError as err:
    print(f"configuration problem: {err}")
```

### Exit-code contracts

Return the exit code a provided contract assigns to whatever exception
ended the program:

```python
import sys

from vcti.error.contract.legacy import exit_code


def main() -> int:
    try:
        run()
        return 0
    except Exception as err:
        return exit_code(err)   # FileNotFoundError -> 2; anything unmapped -> 1


if __name__ == "__main__":
    sys.exit(main())
```

Add your program's own codes to a provided contract:

```python
from vcti.error.contract import legacy
from vcti.error.mechanics import combine, resolve_code
from myapp.errors import CODE_MAP as APP_CODES   # your own contract

CODE_MAP = combine(legacy.CODE_MAP, APP_CODES)   # raises if both map one class differently


def main() -> int:
    try:
        run()
        return 0
    except Exception as err:
        return resolve_code(err, CODE_MAP, default=legacy.ExitCode.UNSPECIFIED)
```

Or define a contract as a plain dictionary:

```python
import sys

from vcti.error.mechanics import resolve_code, validate

CODE_MAP = {FileNotFoundError: 2, PermissionError: 3}
validate(CODE_MAP)   # every code an int in 1..255

try:
    run()
except Exception as err:
    sys.exit(resolve_code(err, CODE_MAP, default=1))
```

### OS errors with `errno` set

`system_error()` builds an OS exception the way the operating system
would, with `errno`, `strerror` and `filename` filled in:

```python
from vcti.error.mechanics import system_error

err = system_error(FileNotFoundError, "config.yaml")
# err.errno == errno.ENOENT, err.filename == "config.yaml"
```

---

## Shared exception classes (`vcti.error.errors`)

| Class | Raise when |
|-------|------------|
| `ConfigError` | Configuration is invalid or missing |
| `DataFormatError` | Input data does not match the expected format |
| `LicenseError` | License validation fails |
| `VariableUndefined` | An undefined workflow variable is referenced |

Each class derives directly from `Exception`; subclass one to describe
a more specific failure. A class has no exit code of its own — each
contract decides which code, if any, it maps the class to.

---

## Exit-code contracts

### How a contract resolves an exception

A contract is a read-only mapping from exception classes to exit codes.
Resolution follows the exception's class hierarchy: the nearest mapped
base class decides the code, so a `class QuotaExceeded(LicenseError)`
gets `LicenseError`'s code. An exception with nothing mapped in its
hierarchy gets the contract's default, its `UNSPECIFIED` code. A
program uses one contract; the provided contracts number their codes
independently.

### Provided contracts (`vcti.error.contract`)

| Module | Codes | Stability |
|--------|-------|-----------|
| `vcti.error.contract.legacy` | `UNSPECIFIED`(1), `FILE_NOT_FOUND`(2), `LICENSE_ERROR`(3), `KEY_ERROR`(4), `VARIABLE_UNDEFINED`(5) | Stable — a released code never changes; new codes may be added within 1–5 |
| `vcti.error.contract.base_draft` | 11 codes within 1–63, among them `INVALID_INPUT`, `PERMISSION_DENIED`, `CONFIG_ERROR`, `DATA_FORMAT_ERROR` | Draft — may change in any release; not for production use |

Every contract module exposes the same four names:

| Name | Purpose |
|------|---------|
| `ExitCode` | `IntEnum` of the contract's codes |
| `CODE_MAP` | The read-only class → code mapping |
| `exit_code(exc)` | Exception (instance or class) → exit code |
| `exception_class(code)` | Exit code → exception class (`Exception` if unmapped) |

To publish a contract of your own, see
[docs/extending.md](docs/extending.md).

### Mechanics (`vcti.error.mechanics`)

| Name | Kind | Purpose |
|------|------|---------|
| `CodeMap` | type alias | `Mapping[type[BaseException], int]` — a contract |
| `validate(code_map, *, claim)` | function | Checks keys and codes; `claim` limits codes to a declared range |
| `combine(*code_maps)` | function | Read-only merge; one class mapped to two codes → `CodeCollisionError` |
| `resolve_code(exc, code_map, *, default)` | function | Exception → code, by class hierarchy; `default` when nothing matches |
| `resolve_class(code, code_map, *, default=Exception)` | function | Code → exception class (one class if several share a code) |
| `bind(code_map, *, default)` | function | Returns the `(exit_code, exception_class)` pair for a contract |
| `system_error(cls, *args)` | function | Builds an OS exception with the matching `errno` |
| `ERRNO_MAP` | constant | Read-only OS-exception → errno table used by `system_error` |
| `MAX_EXIT_CODE` | constant | 255, the highest exit code a process can report |
| `CodeMapError` | exception | Base of `CodeRangeError` and `CodeCollisionError` |

`validate()` accepts codes 1–255 — 0 means success, and the operating
system keeps only the low 8 bits, so 256 would arrive as 0 — and
rejects `bool` codes. Keep codes at or below 125: shells and process
tools reserve 126 and above.

---

## Dependencies

None. Standard library only.

---

## Documentation

| If you want to… | Read |
|---|---|
| Get started using the package | [Quick Start](#quick-start) above |
| Understand the architecture and the design decisions | [docs/design.md](docs/design.md) |
| Navigate and understand the source | [docs/source-guide.md](docs/source-guide.md) |
| See practical, real-world usage | [docs/patterns.md](docs/patterns.md) |
| Extend the library (add a shared class or a contract) | [docs/extending.md](docs/extending.md) |
