1from __future__ import annotations
2
3import http
4import typing
5import warnings
6
7__all__ = ("HTTPException", "WebSocketException")
8
9
10class HTTPException(Exception):
11 def __init__(
12 self,
13 status_code: int,
14 detail: str | None = None,
15 headers: dict[str, str] | None = None,
16 ) -> None:
17 if detail is None:
18 detail = http.HTTPStatus(status_code).phrase
19 self.status_code = status_code
20 self.detail = detail
21 self.headers = headers
22
23 def __str__(self) -> str:
24 return f"{self.status_code}: {self.detail}"
25
26 def __repr__(self) -> str:
27 class_name = self.__class__.__name__
28 return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"
29
30
31class WebSocketException(Exception):
32 def __init__(self, code: int, reason: str | None = None) -> None:
33 self.code = code
34 self.reason = reason or ""
35
36 def __str__(self) -> str:
37 return f"{self.code}: {self.reason}"
38
39 def __repr__(self) -> str:
40 class_name = self.__class__.__name__
41 return f"{class_name}(code={self.code!r}, reason={self.reason!r})"
42
43
44__deprecated__ = "ExceptionMiddleware"
45
46
47def __getattr__(name: str) -> typing.Any: # pragma: no cover
48 if name == __deprecated__:
49 from starlette.middleware.exceptions import ExceptionMiddleware
50
51 warnings.warn(
52 f"{__deprecated__} is deprecated on `starlette.exceptions`. "
53 f"Import it from `starlette.middleware.exceptions` instead.",
54 category=DeprecationWarning,
55 stacklevel=3,
56 )
57 return ExceptionMiddleware
58 raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
59
60
61def __dir__() -> list[str]:
62 return sorted(list(__all__) + [__deprecated__]) # pragma: no cover