From 4893b798b8ec8fc638980ad95d9f8558805f9174 Mon Sep 17 00:00:00 2001 From: chandlernine <62032675+chandlernine@users.noreply.github.com> Date: Sun, 21 Mar 2021 02:55:20 -0400 Subject: [PATCH 1/2] Stops calling got_request_exception for exceptions explicitly handled. --- flask_restx/api.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/flask_restx/api.py b/flask_restx/api.py index 4221db39..60157088 100644 --- a/flask_restx/api.py +++ b/flask_restx/api.py @@ -679,8 +679,6 @@ def handle_error(self, e): :param Exception e: the raised Exception object """ - got_request_exception.send(current_app._get_current_object(), exception=e) - # When propagate_exceptions is set, do not return the exception to the # client if a handler is configured for the exception. if ( @@ -710,6 +708,10 @@ def handle_error(self, e): ) break else: + # Flask docs say: "This signal is not sent for HTTPException or other exceptions that have error handlers + # registered, unless the exception was raised from an error handler." + got_request_exception.send(current_app._get_current_object(), exception=e) + if isinstance(e, HTTPException): code = HTTPStatus(e.code) if include_message_in_response: From 872cc97f632c58246c24d09b9a4d222f141c7757 Mon Sep 17 00:00:00 2001 From: Volker Austrup Date: Mon, 5 Jul 2021 19:36:01 +0200 Subject: [PATCH 2/2] add test for not always calling got_request_exception --- tests/test_errors.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/test_errors.py b/tests/test_errors.py index e1ce03ff..9638ef11 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -444,6 +444,27 @@ def record(sender, exception): finally: got_request_exception.disconnect(record, app) + def test_handle_error_signal_does_not_call_got_request_exception(self, app): + api = restx.Api(app) + + exception = BadRequest() + + recorded = [] + + def record(sender, exception): + recorded.append(exception) + + @api.errorhandler(BadRequest) + def handle_bad_request(error): + return {"message": str(error), "value": "test"}, 400 + + got_request_exception.connect(record, app) + try: + api.handle_error(exception) + assert len(recorded) == 0 + finally: + got_request_exception.disconnect(record, app) + def test_handle_error(self, app): api = restx.Api(app)