Coverage for fastblocks / exceptions.py: 95%
126 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1import typing as t
2from abc import ABC, abstractmethod
3from contextlib import suppress
4from dataclasses import dataclass
5from enum import Enum
6from operator import itemgetter
8from oneiric.core.resolution import Resolver
9from starlette.exceptions import HTTPException
10from starlette.requests import Request
11from starlette.responses import PlainTextResponse, Response
12from fastblocks.htmx import HtmxRequest
14# Replace ACB depends with Oneiric Resolver
15depends = Resolver()
17_templates_cache = None
20class ErrorSeverity(Enum):
21 CRITICAL = "critical"
22 ERROR = "error"
23 WARNING = "warning"
24 INFO = "info"
27class ErrorCategory(Enum):
28 CONFIGURATION = "configuration"
29 DEPENDENCY = "dependency"
30 AUTHENTICATION = "authentication"
31 AUTHORIZATION = "authorization"
32 VALIDATION = "validation"
33 CACHING = "caching"
34 TEMPLATE = "template"
35 MIDDLEWARE = "middleware"
36 APPLICATION = "application"
39@dataclass
40class ErrorContext:
41 error_id: str
42 category: ErrorCategory
43 severity: ErrorSeverity
44 message: str
45 details: dict[str, t.Any] | None = None
46 request_id: str | None = None
47 user_id: str | None = None
50class ErrorHandler(ABC):
51 @abstractmethod
52 async def can_handle(self, exception: Exception, context: ErrorContext) -> bool:
53 pass
55 @abstractmethod
56 async def handle(
57 self,
58 exception: Exception,
59 context: ErrorContext,
60 request: Request,
61 ) -> Response:
62 pass
65class ErrorHandlerRegistry:
66 def __init__(self) -> None:
67 self._handlers: list[tuple[int, ErrorHandler]] = []
68 self._fallback_handler: ErrorHandler | None = None
70 def register(self, handler: ErrorHandler, priority: int = 0) -> None:
71 self._handlers.append((priority, handler))
72 self._handlers.sort(key=itemgetter(0), reverse=True)
74 def set_fallback(self, handler: ErrorHandler) -> None:
75 self._fallback_handler = handler
77 async def handle_error(
78 self,
79 exception: Exception,
80 context: ErrorContext,
81 request: Request,
82 ) -> Response:
83 for _, handler in self._handlers:
84 if await handler.can_handle(exception, context):
85 return await handler.handle(exception, context, request)
87 if self._fallback_handler:
88 return await self._fallback_handler.handle(exception, context, request)
90 return PlainTextResponse("Internal Server Error", status_code=500)
93class DefaultErrorHandler(ErrorHandler):
94 async def can_handle(self, exception: Exception, context: ErrorContext) -> bool:
95 return True
97 async def handle(
98 self,
99 exception: Exception,
100 context: ErrorContext,
101 request: Request,
102 ) -> Response:
103 status_code = getattr(exception, "status_code", 500)
104 message = {404: "Content not found", 500: "Server error"}.get(
105 status_code,
106 "An error occurred",
107 )
109 if hasattr(request, "scope") and request.scope.get("htmx"):
110 return PlainTextResponse(content=message, status_code=status_code)
112 templates = await safe_depends_get("templates", _exception_cache)
113 if templates:
114 with suppress(Exception):
115 result = await templates.app.render_template(
116 request,
117 "index.html",
118 status_code=status_code,
119 context={"page": str(status_code)},
120 )
121 return t.cast(Response, result)
123 return PlainTextResponse(content=message, status_code=status_code)
126_error_registry = ErrorHandlerRegistry()
127_error_registry.set_fallback(DefaultErrorHandler())
130def register_error_handler(handler: ErrorHandler, priority: int = 0) -> None:
131 _error_registry.register(handler, priority)
134async def safe_depends_get(
135 key: str,
136 cache_dict: dict[str, t.Any],
137 default: t.Any = None,
138) -> t.Any:
139 if key not in cache_dict:
140 try:
141 cache_dict[key] = await depends.resolve("fastblocks", key)
142 except Exception:
143 cache_dict[key] = default
144 return cache_dict[key]
147_exception_cache: dict[t.Any, t.Any] = {}
150async def handle_exception(request: HtmxRequest, exc: HTTPException) -> Response:
151 status_code = getattr(exc, "status_code", 500)
152 error_context = ErrorContext(
153 error_id=f"http_{status_code}",
154 category=ErrorCategory.APPLICATION,
155 severity=ErrorSeverity.ERROR if status_code >= 500 else ErrorSeverity.WARNING,
156 message=exc.detail if hasattr(exc, "detail") else f"HTTP {status_code}",
157 details={
158 "status_code": status_code,
159 "request_path": getattr(getattr(request, "url", None), "path", "/")
160 if getattr(request, "url", None)
161 else "/",
162 },
163 )
164 if hasattr(request, "scope") and hasattr(request, "receive"):
165 from starlette.requests import Request
167 scope = getattr(request, "scope", {})
168 receive = getattr(request, "receive", None)
169 if scope and receive:
170 starlette_request = Request(scope, receive)
171 return await _error_registry.handle_error(
172 exc, error_context, starlette_request
173 )
174 return await _error_registry.handle_error(
175 exc, error_context, t.cast(t.Any, request)
176 )
179class FastBlocksException(Exception):
180 def __init__(
181 self,
182 message: str,
183 category: ErrorCategory = ErrorCategory.APPLICATION,
184 severity: ErrorSeverity = ErrorSeverity.ERROR,
185 details: dict[str, t.Any] | None = None,
186 status_code: int | None = None,
187 ) -> None:
188 super().__init__(message)
189 self.message = message
190 self.category = category
191 self.severity = severity
192 self.details = details if details is not None else {}
193 self.status_code = status_code
195 def to_error_context(self, error_id: str | None = None) -> ErrorContext:
196 return ErrorContext(
197 error_id=error_id or str(self.__class__.__name__.lower()),
198 category=self.category,
199 severity=self.severity,
200 message=self.message,
201 details=self.details,
202 )
205class ConfigurationError(FastBlocksException):
206 def __init__(self, message: str, config_key: str | None = None) -> None:
207 details = {"config_key": config_key} if config_key else {}
208 super().__init__(
209 message,
210 category=ErrorCategory.CONFIGURATION,
211 severity=ErrorSeverity.CRITICAL,
212 details=details,
213 )
216class DependencyError(FastBlocksException):
217 def __init__(self, message: str, dependency_key: str | None = None) -> None:
218 details = {"dependency_key": dependency_key} if dependency_key else {}
219 super().__init__(
220 message,
221 category=ErrorCategory.DEPENDENCY,
222 severity=ErrorSeverity.ERROR,
223 details=details,
224 )
227class StarletteCachesException(FastBlocksException):
228 def __init__(self, message: str = "Cache operation failed") -> None:
229 super().__init__(message, category=ErrorCategory.CACHING)
232class DuplicateCaching(StarletteCachesException):
233 def __init__(self, message: str = "Duplicate cache middleware detected") -> None:
234 super().__init__(message)
237class MissingCaching(StarletteCachesException):
238 def __init__(self, message: str = "Cache middleware not found") -> None:
239 super().__init__(message)
242class RequestNotCachable(StarletteCachesException):
243 def __init__(self, request: Request) -> None:
244 self.request = request
245 super().__init__(
246 f"Request {request.method} {request.url.path} is not cacheable",
247 )
250class ResponseNotCachable(StarletteCachesException):
251 def __init__(self, response: Response) -> None:
252 self.response = response
253 super().__init__(
254 f"Response with status {response.status_code} is not cacheable",
255 )