Browse Source

Use HandledException class instead tuple

Bastien Sevajol 6 years ago
parent
commit
4d3fc94a73
5 changed files with 36 additions and 25 deletions
  1. 18 5
      hapic/context.py
  2. 6 5
      hapic/ext/bottle/context.py
  3. 2 5
      hapic/ext/flask/context.py
  4. 2 4
      hapic/ext/pyramid/context.py
  5. 8 6
      tests/base.py

+ 18 - 5
hapic/context.py View File

@@ -129,6 +129,19 @@ class ContextInterface(object):
129 129
         raise NotImplementedError()
130 130
 
131 131
 
132
+class HandledException(object):
133
+    """
134
+    Representation of an handled exception with it's http code
135
+    """
136
+    def __init__(
137
+        self,
138
+        exception_class: typing.Type[Exception],
139
+        http_code: int = 500,
140
+    ):
141
+        self.exception_class = exception_class
142
+        self.http_code = http_code
143
+
144
+
132 145
 class BaseContext(ContextInterface):
133 146
     def get_default_error_builder(self) -> ErrorBuilderInterface:
134 147
         """ see hapic.context.ContextInterface#get_default_error_builder"""
@@ -166,17 +179,17 @@ class BaseContext(ContextInterface):
166 179
             except Exception as exc:
167 180
                 # Reverse list to read first user given exception before
168 181
                 # the hapic default Exception catch
169
-                handled = reversed(
182
+                handled_exceptions = reversed(
170 183
                     self._get_handled_exception_class_and_http_codes(),
171 184
                 )
172
-                for handled_exception_class, http_code in handled:
185
+                for handled_exception in handled_exceptions:
173 186
                     # TODO BS 2018-05-04: How to be attentive to hierarchy ?
174
-                    if isinstance(exc, handled_exception_class):
187
+                    if isinstance(exc, handled_exception.exception_class):
175 188
                         error_builder = self.get_default_error_builder()
176 189
                         error_body = error_builder.build_from_exception(exc)
177 190
                         return self.get_response(
178 191
                             json.dumps(error_body),
179
-                            http_code,
192
+                            handled_exception.http_code,
180 193
                         )
181 194
                 raise exc
182 195
 
@@ -184,7 +197,7 @@ class BaseContext(ContextInterface):
184 197
 
185 198
     def _get_handled_exception_class_and_http_codes(
186 199
         self,
187
-    ) -> typing.List[typing.Tuple[typing.Type[Exception], int]]:
200
+    ) -> typing.List[HandledException]:
188 201
         """
189 202
         :return: A list of tuple where: thirst item of tuple is a exception
190 203
         class and second tuple item is a http code. This list will be used by

+ 6 - 5
hapic/ext/bottle/context.py View File

@@ -12,6 +12,7 @@ import bottle
12 12
 from multidict import MultiDict
13 13
 
14 14
 from hapic.context import BaseContext
15
+from hapic.context import HandledException
15 16
 from hapic.context import RouteRepresentation
16 17
 from hapic.decorator import DecoratedController
17 18
 from hapic.decorator import DECORATION_ATTRIBUTE_NAME
@@ -33,7 +34,7 @@ class BottleContext(BaseContext):
33 34
         app: bottle.Bottle,
34 35
         default_error_builder: ErrorBuilderInterface=None,
35 36
     ):
36
-        self._handled_exception_and_http_codes = []  # type: typing.List[typing.Tuple[typing.Type[Exception], int]]  # nopep8
37
+        self._handled_exceptions = []  # type: typing.List[HandledException]  # nopep8
37 38
         self._exceptions_handler_installed = False
38 39
         self.app = app
39 40
         self.default_error_builder = \
@@ -145,8 +146,8 @@ class BottleContext(BaseContext):
145 146
         if not self._exceptions_handler_installed:
146 147
             self._install_exceptions_handler()
147 148
 
148
-        self._handled_exception_and_http_codes.append(
149
-            (exception_class, http_code),
149
+        self._handled_exceptions.append(
150
+            HandledException(exception_class, http_code),
150 151
         )
151 152
 
152 153
     def _install_exceptions_handler(self) -> None:
@@ -154,8 +155,8 @@ class BottleContext(BaseContext):
154 155
 
155 156
     def _get_handled_exception_class_and_http_codes(
156 157
         self,
157
-    ) -> typing.List[typing.Tuple[typing.Type[Exception], int]]:
158
+    ) -> typing.List[HandledException]:
158 159
         """
159 160
         See hapic.context.BaseContext#_get_handled_exception_class_and_http_codes  # nopep8
160 161
         """
161
-        return self._handled_exception_and_http_codes
162
+        return self._handled_exceptions

+ 2 - 5
hapic/ext/flask/context.py View File

@@ -33,7 +33,7 @@ class FlaskContext(BaseContext):
33 33
         app: Flask,
34 34
         default_error_builder: ErrorBuilderInterface=None,
35 35
     ):
36
-        self._handled_exception_and_http_codes = []  # type: typing.List[typing.Tuple[typing.Type[Exception], int]]  # nopep8
36
+        self._handled_exceptions = []  # type: typing.List[HandledException]  # nopep8
37 37
         self.app = app
38 38
         self.default_error_builder = \
39 39
             default_error_builder or DefaultErrorBuilder()  # FDV
@@ -164,7 +164,4 @@ class FlaskContext(BaseContext):
164 164
         exception_class: typing.Type[Exception],
165 165
         http_code: int,
166 166
     ) -> None:
167
-        self._handled_exception_and_http_codes.append(
168
-            (exception_class, http_code),
169
-        )
170
-
167
+        raise NotImplementedError('TODO')

+ 2 - 4
hapic/ext/pyramid/context.py View File

@@ -32,7 +32,7 @@ class PyramidContext(BaseContext):
32 32
         configurator: 'Configurator',
33 33
         default_error_builder: ErrorBuilderInterface = None,
34 34
     ):
35
-        self._handled_exception_and_http_codes = []  # type: typing.List[typing.Tuple[typing.Type[Exception], int]]  # nopep8
35
+        self._handled_exceptions = []  # type: typing.List[HandledException]  # nopep8
36 36
         self.configurator = configurator
37 37
         self.default_error_builder = \
38 38
             default_error_builder or DefaultErrorBuilder()  # FDV
@@ -188,6 +188,4 @@ class PyramidContext(BaseContext):
188 188
         exception_class: typing.Type[Exception],
189 189
         http_code: int,
190 190
     ) -> None:
191
-        self._handled_exception_and_http_codes.append(
192
-            (exception_class, http_code),
193
-        )
191
+        raise NotImplementedError('TODO')

+ 8 - 6
tests/base.py View File

@@ -1,17 +1,19 @@
1 1
 # -*- coding: utf-8 -*-
2 2
 import json
3 3
 import typing
4
+
5
+
4 6
 try:  # Python 3.5+
5 7
     from http import HTTPStatus
6 8
 except ImportError:
7 9
     from http import client as HTTPStatus
8 10
 
9 11
 from multidict import MultiDict
10
-import bottle
11 12
 
12 13
 from hapic.ext.bottle import BottleContext
13 14
 from hapic.processor import RequestParameters
14 15
 from hapic.processor import ProcessValidationError
16
+from hapic.context import HandledException
15 17
 
16 18
 
17 19
 class Base(object):
@@ -31,7 +33,7 @@ class MyContext(BottleContext):
31 33
         fake_files_parameters=None,
32 34
     ) -> None:
33 35
         super().__init__(app=app)
34
-        self._handled_exception_and_http_codes = []  # type: typing.List[typing.Tuple[typing.Type[Exception], int]]  # nopep8
36
+        self._handled_exceptions = []  # type: typing.List[HandledException]  # nopep8
35 37
         self._exceptions_handler_installed = False
36 38
         self.fake_path_parameters = fake_path_parameters or {}
37 39
         self.fake_query_parameters = fake_query_parameters or MultiDict()
@@ -73,11 +75,11 @@ class MyContext(BottleContext):
73 75
     ) -> None:
74 76
         if not self._exceptions_handler_installed:
75 77
             self._install_exceptions_handler()
76
-        self._handled_exception_and_http_codes.append(
77
-            (exception_class, http_code),
78
+        self._handled_exceptions.append(
79
+            HandledException(exception_class, http_code),
78 80
         )
79 81
 
80 82
     def _get_handled_exception_class_and_http_codes(
81 83
         self,
82
-    ) -> typing.List[typing.Tuple[typing.Type[Exception], int]]:
83
-        return self._handled_exception_and_http_codes
84
+    ) -> typing.List[HandledException]:
85
+        return self._handled_exceptions