-
-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy patherrors.py
118 lines (87 loc) · 3.05 KB
/
errors.py
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import logging
import traceback
from functools import partial
from typing import TYPE_CHECKING, List, Optional
from django.conf import settings
from django.http import Http404, HttpRequest, HttpResponse
from ninja.types import DictStrAny
if TYPE_CHECKING:
from ninja import NinjaAPI # pragma: no cover
__all__ = [
"ConfigError",
"AuthenticationError",
"ValidationError",
"HttpError",
"set_default_exc_handlers",
]
logger = logging.getLogger("django")
class ConfigError(Exception):
pass
class AuthenticationError(Exception):
pass
class ValidationError(Exception):
"""
This exception raised when operation params do not validate
Note: this is not the same as pydantic.ValidationError
the errors attribute as well holds the location of the error(body, form, query, etc.)
"""
def __init__(self, errors: List[DictStrAny]) -> None:
self.errors = errors
super().__init__(errors)
class HttpError(Exception):
def __init__(self, status_code: int, message: str) -> None:
self.status_code = status_code
self.message = message
super().__init__(status_code, message)
def __str__(self) -> str:
return self.message
class Throttled(HttpError):
def __init__(self, wait: Optional[int]) -> None:
self.wait = wait
super().__init__(status_code=429, message="Too many requests.")
def set_default_exc_handlers(api: "NinjaAPI") -> None:
api.add_exception_handler(
Exception,
partial(_default_exception, api=api),
)
api.add_exception_handler(
Http404,
partial(_default_404, api=api),
)
api.add_exception_handler(
HttpError,
partial(_default_http_error, api=api),
)
api.add_exception_handler(
ValidationError,
partial(_default_validation_error, api=api),
)
api.add_exception_handler(
AuthenticationError,
partial(_default_authentication_error, api=api),
)
def _default_404(request: HttpRequest, exc: Exception, api: "NinjaAPI") -> HttpResponse:
msg = "Not Found"
if settings.DEBUG:
msg += f": {exc}"
return api.create_response(request, {"detail": msg}, status=404)
def _default_http_error(
request: HttpRequest, exc: HttpError, api: "NinjaAPI"
) -> HttpResponse:
return api.create_response(request, {"detail": str(exc)}, status=exc.status_code)
def _default_validation_error(
request: HttpRequest, exc: ValidationError, api: "NinjaAPI"
) -> HttpResponse:
return api.create_response(request, {"detail": exc.errors}, status=422)
def _default_authentication_error(
request: HttpRequest, exc: AuthenticationError, api: "NinjaAPI"
) -> HttpResponse:
return api.create_response(request, {"detail": "Unauthorized"}, status=401)
def _default_exception(
request: HttpRequest, exc: Exception, api: "NinjaAPI"
) -> HttpResponse:
if not settings.DEBUG:
raise exc # let django deal with it
logger.exception(exc)
tb = traceback.format_exc()
return HttpResponse(tb, status=500, content_type="text/plain")