team-hermes.core 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ """Shared application exceptions."""
2
+
3
+ from .exceptions import (
4
+ ApplicationException,
5
+ BusinessRuleViolationException,
6
+ ConflictException,
7
+ DuplicateException,
8
+ ExceptionSeverity,
9
+ MissingPrivilegeException,
10
+ NotFoundException,
11
+ UnauthorizedException,
12
+ UpstreamApiException,
13
+ ValidationException,
14
+ )
15
+
16
+ __all__ = [
17
+ "ApplicationException",
18
+ "BusinessRuleViolationException",
19
+ "ConflictException",
20
+ "DuplicateException",
21
+ "ExceptionSeverity",
22
+ "MissingPrivilegeException",
23
+ "NotFoundException",
24
+ "UnauthorizedException",
25
+ "UpstreamApiException",
26
+ "ValidationException",
27
+ ]
@@ -0,0 +1,160 @@
1
+ """Application exceptions independent of transport and persistence frameworks."""
2
+
3
+ from enum import Enum, unique
4
+ from typing import Any
5
+
6
+
7
+ @unique
8
+ class ExceptionSeverity(Enum):
9
+ WARNING = 1
10
+ ERROR = 2
11
+ CRITICAL = 3
12
+
13
+
14
+ class ApplicationException(Exception):
15
+ """Base class for application-specific exceptions."""
16
+
17
+ def __init__(
18
+ self,
19
+ type: str = "about:blank",
20
+ title: str | None = None,
21
+ detail: str | None = None,
22
+ instance: str | None = None,
23
+ extensions: dict[str, Any] | None = None,
24
+ severity: ExceptionSeverity = ExceptionSeverity.ERROR,
25
+ *,
26
+ errors: list[dict[str, Any]] | None = None,
27
+ ) -> None:
28
+ super().__init__(detail)
29
+ self.type = type
30
+ self.title = title
31
+ self.detail = detail
32
+ self.instance = instance
33
+ self.extensions = extensions
34
+ self.severity = severity
35
+ self.errors = errors
36
+
37
+ def to_dict(self) -> dict[str, Any]:
38
+ return {
39
+ "type": self.type,
40
+ "title": self.title,
41
+ "detail": self.detail,
42
+ "instance": self.instance,
43
+ "extensions": self.extensions,
44
+ "severity": self.severity.name if self.severity else None,
45
+ **({"errors": self.errors} if self.errors is not None else {}),
46
+ }
47
+
48
+
49
+ class MissingPrivilegeException(ApplicationException):
50
+ """Raised when a user lacks necessary privileges."""
51
+
52
+ def __init__(
53
+ self,
54
+ detail: str = "You do not have the required permissions.",
55
+ title: str = "Forbidden",
56
+ extensions: dict[str, Any] | None = None,
57
+ ) -> None:
58
+ super().__init__(
59
+ type="/docs/problems/forbidden",
60
+ title=title,
61
+ detail=detail,
62
+ extensions=extensions,
63
+ severity=ExceptionSeverity.WARNING,
64
+ )
65
+
66
+
67
+ class NotFoundException(ApplicationException):
68
+ """Raised when a requested resource is not found."""
69
+
70
+ def __init__(
71
+ self,
72
+ detail: str = "The requested resource could not be found.",
73
+ title: str = "Not Found",
74
+ extensions: dict[str, Any] | None = None,
75
+ ) -> None:
76
+ super().__init__(type="/docs/problems/not-found", title=title, detail=detail, extensions=extensions)
77
+
78
+
79
+ class ValidationException(ApplicationException):
80
+ """Raised when input data fails validation."""
81
+
82
+ def __init__(
83
+ self,
84
+ detail: str = "The received data is invalid.",
85
+ title: str = "Unprocessable Entity",
86
+ extensions: dict[str, Any] | None = None,
87
+ *,
88
+ errors: list[dict[str, Any]] | None = None,
89
+ ) -> None:
90
+ super().__init__(
91
+ type="/docs/problems/validation-error", title=title, detail=detail, extensions=extensions, errors=errors
92
+ )
93
+
94
+
95
+ class UnauthorizedException(ApplicationException):
96
+ """Raised when authentication fails."""
97
+
98
+ def __init__(
99
+ self,
100
+ detail: str = "Token validation failed.",
101
+ title: str = "Unauthorized",
102
+ extensions: dict[str, Any] | None = None,
103
+ ) -> None:
104
+ super().__init__(type="/docs/problems/unauthorized", title=title, detail=detail, extensions=extensions)
105
+
106
+
107
+ class BusinessRuleViolationException(ApplicationException):
108
+ """Raised when an operation violates a business rule."""
109
+
110
+ def __init__(
111
+ self,
112
+ detail: str = "The requested operation violates a business rule.",
113
+ title: str = "Business Rule Violation",
114
+ extensions: dict[str, Any] | None = None,
115
+ ) -> None:
116
+ super().__init__(
117
+ type="/docs/problems/business-rule-violation", title=title, detail=detail, extensions=extensions
118
+ )
119
+
120
+
121
+ class DuplicateException(ApplicationException):
122
+ """Raised when attempting to create a duplicate resource."""
123
+
124
+ def __init__(
125
+ self,
126
+ detail: str = "A resource with the same identifier already exists.",
127
+ title: str = "Duplicate",
128
+ extensions: dict[str, Any] | None = None,
129
+ ) -> None:
130
+ super().__init__(type="/docs/problems/duplicate", title=title, detail=detail, extensions=extensions)
131
+
132
+
133
+ class ConflictException(ApplicationException):
134
+ """Raised when an operation conflicts with the current resource state."""
135
+
136
+ def __init__(
137
+ self,
138
+ detail: str = "The request could not be completed due to a conflict with the current state of the resource.",
139
+ title: str = "Conflict",
140
+ extensions: dict[str, Any] | None = None,
141
+ ) -> None:
142
+ super().__init__(type="/docs/problems/conflict", title=title, detail=detail, extensions=extensions)
143
+
144
+
145
+ class UpstreamApiException(ApplicationException):
146
+ """Raised when an upstream API returns an unexpected or malformed response."""
147
+
148
+ def __init__(
149
+ self,
150
+ detail: str = "An upstream API returned an unexpected response.",
151
+ title: str = "Upstream API Error",
152
+ extensions: dict[str, Any] | None = None,
153
+ ) -> None:
154
+ super().__init__(
155
+ type="/docs/problems/upstream-api-error",
156
+ title=title,
157
+ detail=detail,
158
+ extensions=extensions,
159
+ severity=ExceptionSeverity.ERROR,
160
+ )
@@ -0,0 +1 @@
1
+ # PEP 561 marker for inline type information.
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.5
2
+ Name: team-hermes.core
3
+ Version: 1.0.1
4
+ Summary: Shared application exceptions for Team Hermes projects
5
+ Project-URL: Repository, https://github.com/equinor/team-hermes-packages
6
+ Project-URL: Issues, https://github.com/equinor/team-hermes-packages/issues
7
+ License-File: LICENSE.md
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Programming Language :: Python :: 3.15
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Requires-Python: >=3.12
17
+ Description-Content-Type: text/markdown
18
+
19
+ # 🧩 Team Hermes Core
20
+
21
+ Shared, framework- and transport-agnostic Python exceptions for application failures.
22
+ They describe what went wrong without knowing about HTTP APIs, status codes, or
23
+ response formats. Your application or integration decides how to handle them,
24
+ whether in an API, command-line tool, or background worker.
25
+
26
+ **Requires:** Python 3.12+. Git is required for installation from source.
27
+ Core has no runtime dependencies outside the standard library.
28
+
29
+ ## ⬇️ Installation
30
+
31
+ Install into a virtual environment:
32
+
33
+ ```shell
34
+ python -m pip install \
35
+ "team-hermes-core @ git+https://github.com/equinor/team-hermes-packages.git@main#subdirectory=team-hermes-packages-python/core"
36
+ ```
37
+
38
+ For reproducible installs, replace `main` with a release tag or full commit SHA.
39
+
40
+ ## Quick Start
41
+
42
+ Import from `team_hermes.core`, raise a specific exception, and catch it where you
43
+ can handle the failure. `ApplicationException` catches any of the built-in categories:
44
+
45
+ ```pycon
46
+ >>> from team_hermes.core import ApplicationException, NotFoundException
47
+ >>> orders = {"order-1": "pending"}
48
+ >>> def get_order_status(order_id: str) -> str:
49
+ ... if order_id not in orders:
50
+ ... raise NotFoundException("Order not found", extensions={"order_id": order_id})
51
+ ... return orders[order_id]
52
+ ...
53
+ >>> try:
54
+ ... status = get_order_status("order-404")
55
+ ... print(status)
56
+ ... except ApplicationException as error:
57
+ ... print(str(error))
58
+ ...
59
+ Order not found
60
+
61
+ ```
62
+
63
+ The caller decides how to present the error; the lookup function has no logging
64
+ or HTTP dependency.
65
+
66
+ ## Handling Errors
67
+
68
+ Catch a specific exception when you can recover from that failure. Catch
69
+ `ApplicationException` at an application boundary that handles all application
70
+ errors: a CLI might display a message and choose an exit code; a worker might
71
+ record a failed job or apply its own retry policy.
72
+
73
+ Core does not send responses, emit logs, retry operations, or manage database
74
+ transactions. Titles, type identifiers, and severity are metadata, not HTTP status
75
+ mappings. For APIs, the [FastAPI integration](../fastapi-error-handling/README.md#problem-details)
76
+ provides response conversion and logging; applications own disclosure policies.
77
+
78
+ ## Choosing an Exception
79
+
80
+ | Exception | Use when |
81
+ | -------------------------------- | -------------------------------------------------------------------- |
82
+ | `NotFoundException` | A required resource does not exist. |
83
+ | `ValidationException` | Application input is invalid, such as a reversed date range. |
84
+ | `BusinessRuleViolationException` | Valid input violates a policy, such as a purchasing limit. |
85
+ | `ConflictException` | Current resource state prevents an action, such as a stale revision. |
86
+ | `DuplicateException` | Creation would violate uniqueness. |
87
+ | `UnauthorizedException` | Authentication is missing or invalid. |
88
+ | `MissingPrivilegeException` | The caller lacks permission. |
89
+ | `UpstreamApiException` | An upstream API returns an unexpected or malformed response. |
90
+
91
+ All eight inherit directly from `ApplicationException`; `DuplicateException` is
92
+ not a `ConflictException`. Translate only known failures with an application
93
+ meaning, preserving their cause with `raise ... from error`. Do not reclassify
94
+ every unexpected programming error as an application exception.
95
+
96
+ Choose categories consistently so callers can react appropriately. An empty search
97
+ result need not be an exception; use `NotFoundException` when a particular resource
98
+ is required to exist.
99
+
100
+ ## Exception Details
101
+
102
+ - Built-in categories accept `detail`, `title`, and `extensions`. Keep messages
103
+ useful and context safe to disclose: integrations may return them to clients.
104
+ - `MissingPrivilegeException` defaults to `ExceptionSeverity.WARNING`; the others
105
+ default to `ERROR`. The enum also provides `CRITICAL`. Severity is metadata;
106
+ core does not emit logs.
107
+ - The base `ApplicationException` additionally accepts `type`, `instance`, and
108
+ `severity`. Its defaults are `about:blank`, `ERROR`, and `None` for optional fields.
109
+ - `ApplicationException` and `ValidationException` accept keyword-only `errors`,
110
+ a list of dictionaries for safe, structured error details. For example,
111
+ `ValidationException("Invalid order", errors=[{"detail": "Total must be positive", "pointer": "#/total"}])`.
112
+ Core stores these details without interpreting them; the FastAPI integration
113
+ exposes supported fields in the response's top-level `errors` array.
114
+ - `to_dict()` retains `None` for existing fields and shares the original
115
+ extensions dictionary. It includes `errors` only when supplied, including an
116
+ empty list. It is not an HTTP response.
117
+
118
+ ## 🛠️ Development
119
+
120
+ Follow the [workspace setup](../README.md), then run from the repository root:
121
+
122
+ ```shell
123
+ mise run python:test -- core/tests
124
+ mise run python:lint
125
+ mise run python:typecheck
126
+ mise run python:build
127
+ ```
128
+
129
+ The README example is executed and checked by pytest. To test the installed wheel independently:
130
+
131
+ ```shell
132
+ UV_PYTHON=3.12 mise run python:test:core
133
+ ```
134
+
135
+ ## ⚖️ License
136
+
137
+ See [LICENSE.md](LICENSE.md).
@@ -0,0 +1,7 @@
1
+ team_hermes/core/__init__.py,sha256=cmCSzuFBfSKz-DGC_o-WaO1CSb8fMcYZCnYzYlYT4Eg,629
2
+ team_hermes/core/exceptions.py,sha256=Iv_VrdE95V8CNMCGgELc-byXU5qwCHuqZS_as-qRjNI,5164
3
+ team_hermes/core/py.typed,sha256=HzpHl0xcXd5cnxftVZl2KY7aDgf67EodtYQFZ8eygB4,46
4
+ team_hermes_core-1.0.1.dist-info/METADATA,sha256=kmjlhlj8Uogwkjkm7VMicO-kR5-XbgFWn1h93E9RXyM,6166
5
+ team_hermes_core-1.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ team_hermes_core-1.0.1.dist-info/licenses/LICENSE.md,sha256=zefthAHZDOYIcHUXefkN_Fvuy4s-nYfoLX_dsycVDxc,1064
7
+ team_hermes_core-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Equinor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.