@@ -42,11 +42,11 @@ def is_api_request(request: web.Request, api_version: str) -> bool:
4242 return bool (request .path .startswith (base_path ))
4343
4444
45- def _process_and_raise_unexpected_error (
46- request : web .BaseRequest , err : Exception , * , skip_internal_error_details : bool
47- ):
48- """Process unexpected exceptions and raise them as HTTP errors with proper formatting."""
49- error_code = create_error_code (err )
45+ def _handle_unexpected_error (
46+ request : web .BaseRequest , exception : Exception , * , skip_internal_error_details : bool
47+ ) -> web . HTTPInternalServerError :
48+ """Process unexpected exceptions and return them as HTTP errors with proper formatting."""
49+ error_code = create_error_code (exception )
5050 error_context : dict [str , Any ] = {
5151 "request.remote" : f"{ request .remote } " ,
5252 "request.method" : f"{ request .method } " ,
@@ -55,7 +55,7 @@ def _process_and_raise_unexpected_error(
5555
5656 user_error_msg = _FMSG_INTERNAL_ERROR_USER_FRIENDLY
5757 http_error = create_http_error (
58- err ,
58+ exception ,
5959 user_error_msg ,
6060 web .HTTPInternalServerError ,
6161 skip_internal_error_details = skip_internal_error_details ,
@@ -64,79 +64,97 @@ def _process_and_raise_unexpected_error(
6464 _logger .exception (
6565 ** create_troubleshotting_log_kwargs (
6666 user_error_msg ,
67- error = err ,
67+ error = exception ,
6868 error_context = error_context ,
6969 error_code = error_code ,
7070 )
7171 )
72- raise http_error
72+ return http_error
7373
7474
75- def _handle_http_error (err : web .HTTPError ) -> None :
75+ def _handle_http_error (
76+ request : web .BaseRequest , exception : web .HTTPError
77+ ) -> web .HTTPError :
7678 """Handle standard HTTP errors by ensuring they're properly formatted."""
77- err .content_type = MIMETYPE_APPLICATION_JSON
78- if err .reason :
79- err .set_status (err .status , safe_status_message (message = err .reason ))
79+ exception .content_type = MIMETYPE_APPLICATION_JSON
80+ if exception .reason :
81+ exception .set_status (
82+ exception .status , safe_status_message (message = exception .reason )
83+ )
8084
81- if not err .text or not is_enveloped_from_text (err .text ):
82- error_message = err .text or err .reason or "Unexpected error"
85+ if not exception .text or not is_enveloped_from_text (exception .text ):
86+ error_message = exception .text or exception .reason or "Unexpected error"
8387 error_model = ErrorGet (
8488 errors = [
85- ErrorItemType .from_error (err ),
89+ ErrorItemType .from_error (exception ),
8690 ],
87- status = err .status ,
91+ status = exception .status ,
8892 logs = [
8993 LogMessageType (message = error_message , level = "ERROR" ),
9094 ],
9195 message = error_message ,
9296 )
93- err .text = EnvelopeFactory (error = error_model ).as_text ()
97+ exception .text = EnvelopeFactory (error = error_model ).as_text ()
98+
99+ return exception
94100
95101
96102def _handle_http_successful (
97- err : web .HTTPSuccessful , request : web .Request , * , skip_internal_error_details : bool
98- ) -> None :
103+ request : web .Request ,
104+ exception : web .HTTPSuccessful ,
105+ * ,
106+ skip_internal_error_details : bool ,
107+ ) -> web .HTTPSuccessful :
99108 """Handle successful HTTP responses, ensuring they're properly enveloped."""
100- err .content_type = MIMETYPE_APPLICATION_JSON
101- if err .reason :
102- err .set_status (err .status , safe_status_message (message = err .reason ))
109+ exception .content_type = MIMETYPE_APPLICATION_JSON
110+ if exception .reason :
111+ exception .set_status (
112+ exception .status , safe_status_message (message = exception .reason )
113+ )
103114
104- if err .text :
115+ if exception .text :
105116 try :
106- payload = json_loads (err .text )
117+ payload = json_loads (exception .text )
107118 if not is_enveloped_from_map (payload ):
108119 payload = wrap_as_envelope (data = payload )
109- err .text = json_dumps (payload )
120+ exception .text = json_dumps (payload )
110121 except Exception as other_error : # pylint: disable=broad-except
111- _process_and_raise_unexpected_error (
122+ return _handle_unexpected_error (
112123 request ,
113124 other_error ,
114125 skip_internal_error_details = skip_internal_error_details ,
115126 )
116127
128+ return exception
129+
117130
118131def _handle_not_implemented (
119- err : NotImplementedError , * , skip_internal_error_details : bool
120- ) -> None :
132+ request : web .Request ,
133+ exception : NotImplementedError ,
134+ * ,
135+ skip_internal_error_details : bool ,
136+ ) -> web .HTTPNotImplemented :
121137 """Handle NotImplementedError by converting to appropriate HTTP error."""
122138 http_error = create_http_error (
123- err ,
124- f"{ err } " ,
139+ exception ,
140+ f"{ exception } " ,
125141 web .HTTPNotImplemented ,
126142 skip_internal_error_details = skip_internal_error_details ,
127143 )
128- raise http_error from err
144+ return http_error
129145
130146
131- def _handle_timeout (err : TimeoutError , * , skip_internal_error_details : bool ) -> None :
147+ def _handle_timeout (
148+ request : web .Request , exception : TimeoutError , * , skip_internal_error_details : bool
149+ ) -> web .HTTPGatewayTimeout :
132150 """Handle TimeoutError by converting to appropriate HTTP error."""
133151 http_error = create_http_error (
134- err ,
135- f"{ err } " ,
152+ exception ,
153+ f"{ exception } " ,
136154 web .HTTPGatewayTimeout ,
137155 skip_internal_error_details = skip_internal_error_details ,
138156 )
139- raise http_error from err
157+ return http_error
140158
141159
142160def error_middleware_factory ( # noqa: C901
@@ -154,31 +172,32 @@ async def _middleware_handler(request: web.Request, handler: Handler): # noqa:
154172
155173 # FIXME: review when to send info to client and when not!
156174 try :
157- return await handler (request )
158-
159- except web .HTTPError as err :
160- _handle_http_error (err )
161- raise
162-
163- except web .HTTPSuccessful as err :
164- _handle_http_successful (err , request , skip_internal_error_details = _is_prod )
165- raise
166-
167- except web .HTTPRedirection as err :
168- _logger .debug ("Redirected to %s" , err )
169- raise
175+ result = await handler (request )
176+ except web .HTTPError as exc :
177+ result = _handle_http_error (request , exc )
178+ except web .HTTPSuccessful as exc :
179+ result = _handle_http_successful (
180+ request , exc , skip_internal_error_details = _is_prod
181+ )
182+ except web .HTTPRedirection as exc :
183+ _logger .debug ("Redirected to %s" , exc )
184+ raise # We still raise redirection exceptions directly
170185
171- except NotImplementedError as err :
172- _handle_not_implemented (err , skip_internal_error_details = _is_prod )
186+ except NotImplementedError as exc :
187+ result = _handle_not_implemented (
188+ request , exc , skip_internal_error_details = _is_prod
189+ )
173190
174- except TimeoutError as err :
175- _handle_timeout (err , skip_internal_error_details = _is_prod )
191+ except TimeoutError as exc :
192+ result = _handle_timeout (request , exc , skip_internal_error_details = _is_prod )
176193
177- except Exception as err : # pylint: disable=broad-except
178- _process_and_raise_unexpected_error (
179- request , err , skip_internal_error_details = _is_prod
194+ except Exception as exc : # pylint: disable=broad-except
195+ result = _handle_unexpected_error (
196+ request , exc , skip_internal_error_details = _is_prod
180197 )
181198
199+ return result
200+
182201 # adds identifier (mostly for debugging)
183202 _middleware_handler .__middleware_name__ = f"{ __name__ } .error_{ api_version } "
184203
0 commit comments