File size: 1,773 Bytes
0a1b571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from datetime import datetime
from typing import Any, Optional

from pydantic import AnyHttpUrl, BaseModel, Extra, Field


class ExceptionReturn(BaseModel):
    url: Optional[AnyHttpUrl] = None
    time: datetime = Field(default_factory=datetime.now)
    code: int = Field(ge=400, le=599)
    detail: str
    headers: dict[str, str] = {}

    class Config:
        extra = Extra.allow


class BaseServerException(Exception):
    code: int = 500
    detail: str = "Server Fault"
    headers: dict[str, Any] = {}

    def __init__(
        self,
        detail: Optional[str] = None,
        *,
        code: Optional[int] = None,
        headers: Optional[dict[str, Any]] = None,
        **params
    ) -> None:
        self.data = ExceptionReturn(
            detail=detail or self.__class__.detail,
            code=code or self.__class__.code,
            headers=headers or self.__class__.headers,
            **params
        )
        super().__init__(detail)


class BaseHTTPException(BaseServerException):
    pass


class ServerSideException(BaseServerException):
    code = 500
    detail = "Internal Server Error"


class UpstreamAPIException(ServerSideException):
    code = 502
    detail = "Upstram API request failed"


class UncaughtException(ServerSideException):
    code = 500
    detail = "Uncaught exception raised during processing"
    exc: Exception

    @classmethod
    def with_exception(cls, e: Exception):
        c = cls(e.__class__.__qualname__)
        c.exc = e
        return c


class ClientSideException(BaseServerException):
    code = 400
    detail = "Bad Request"


class ValidationException(ClientSideException):
    code = 422


class RateLimitReachedException(ClientSideException):
    code = 429
    detail = "Rate limit reached"