errors.py python
56 lines 1.8 KB
Raw
sha256:2313b6a6353294a0ca08ff579624198da250b99163a86215aed31a905912e360 Land Scooling Lab T0/T2 training contract and seven-tier tests Human minor ⚠ breaking 42 days ago
1 """Stable, sanitized error model for the Scooling Lab API."""
2
3 from __future__ import annotations
4
5 from dataclasses import dataclass
6 from enum import Enum
7
8
9 class ErrorCode(str, Enum):
10 """Public API error codes that do not expose internals."""
11
12 VALIDATION_ERROR = "VALIDATION_ERROR"
13 MALFORMED_JSON = "MALFORMED_JSON"
14 NOT_FOUND = "NOT_FOUND"
15 INVALID_TRANSITION = "INVALID_TRANSITION"
16 QUEUE_LIMIT_EXCEEDED = "QUEUE_LIMIT_EXCEEDED"
17 METHOD_NOT_ALLOWED = "METHOD_NOT_ALLOWED"
18 CONFLICT = "CONFLICT"
19 INTERNAL_ERROR = "INTERNAL_ERROR"
20
21
22 SAFE_ERROR_MESSAGES: dict[ErrorCode, str] = {
23 ErrorCode.VALIDATION_ERROR: "The request is not accepted by the training contract.",
24 ErrorCode.MALFORMED_JSON: "The request body must be valid JSON.",
25 ErrorCode.NOT_FOUND: "The requested training resource was not found.",
26 ErrorCode.INVALID_TRANSITION: "The requested job state change is not allowed.",
27 ErrorCode.QUEUE_LIMIT_EXCEEDED: "The fixture training queue is full.",
28 ErrorCode.METHOD_NOT_ALLOWED: "The HTTP method is not allowed for this route.",
29 ErrorCode.CONFLICT: "The request conflicts with an existing training job.",
30 ErrorCode.INTERNAL_ERROR: "The training service could not complete the request.",
31 }
32
33
34 @dataclass(frozen=True)
35 class ApiError(Exception):
36 """Exception carrying only a stable public code and HTTP status."""
37
38 code: ErrorCode
39 status: int
40
41 @property
42 def message(self) -> str:
43 """Return the public message for the error code."""
44
45 return SAFE_ERROR_MESSAGES[self.code]
46
47
48 def error_payload(error: ApiError) -> dict[str, dict[str, str]]:
49 """Build a safe JSON error payload with no request echo or paths."""
50
51 return {
52 "error": {
53 "code": error.code.value,
54 "message": error.message,
55 }
56 }
File History 1 commit
sha256:2313b6a6353294a0ca08ff579624198da250b99163a86215aed31a905912e360 Land Scooling Lab T0/T2 training contract and seven-tier tests Human minor 42 days ago