-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.py
More file actions
104 lines (86 loc) · 3.02 KB
/
errors.py
File metadata and controls
104 lines (86 loc) · 3.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""Custom exceptions for the Astrology API client."""
from __future__ import annotations
from typing import Any
try:
import httpx
except ImportError:
httpx = None # type: ignore[assignment]
class AstrologyError(Exception):
"""Base exception for all Astrology API errors.
Attributes:
message: Human-readable error message
status_code: HTTP status code (if applicable)
code: Error code from API (if applicable)
details: Additional error details from API response
"""
def __init__(
self,
message: str,
status_code: int | None = None,
code: str | None = None,
details: Any = None,
) -> None:
"""Initialize AstrologyError.
Args:
message: Human-readable error message
status_code: HTTP status code (if applicable)
code: Error code from API (if applicable)
details: Additional error details from API response
"""
super().__init__(message)
self.message = message
self.status_code = status_code
self.code = code
self.details = details
def is_client_error(self) -> bool:
"""Check if error is a client error (4xx status code).
Returns:
True if status code is in 400-499 range
"""
return self.status_code is not None and 400 <= self.status_code < 500
def is_server_error(self) -> bool:
"""Check if error is a server error (5xx status code).
Returns:
True if status code is >= 500
"""
return self.status_code is not None and self.status_code >= 500
@classmethod
def from_response(cls, response: Any) -> AstrologyError:
"""Create AstrologyError from HTTP response.
Args:
response: httpx.Response object
Returns:
AstrologyError instance with extracted details
"""
if httpx is None:
return cls(message="HTTP error occurred", status_code=500)
try:
body = response.json()
return cls(
message=body.get("message", response.text),
status_code=response.status_code,
code=body.get("code"),
details=body,
)
except Exception:
return cls(
message=response.text or f"HTTP {response.status_code}",
status_code=response.status_code,
)
def __str__(self) -> str:
"""Return string representation of error."""
parts = [self.message]
if self.status_code:
parts.append(f"(HTTP {self.status_code})")
if self.code:
parts.append(f"[{self.code}]")
return " ".join(parts)
def __repr__(self) -> str:
"""Return detailed representation of error."""
return (
f"AstrologyError("
f"message={self.message!r}, "
f"status_code={self.status_code!r}, "
f"code={self.code!r}, "
f"details={self.details!r})"
)