diff --git a/sanic/sanic.py b/sanic/sanic.py index b6f9f99e..aeb00fe9 100644 --- a/sanic/sanic.py +++ b/sanic/sanic.py @@ -179,6 +179,13 @@ class Sanic: try: request_started.send(request) + # Fetch handler from router + handler, args, kwargs = self.router.get(request) + if handler is None: + raise ServerError( + ("'None' was returned while requesting a " + "handler from the router")) + # -------------------------------------------- # # Request Middleware # -------------------------------------------- # @@ -196,17 +203,9 @@ class Sanic: # No middleware results if not response: # -------------------------------------------- # - # Execute Handler + # Execute Response Handler # -------------------------------------------- # - # Fetch handler from router - handler, args, kwargs = self.router.get(request) - if handler is None: - raise ServerError( - ("'None' was returned while requesting a " - "handler from the router")) - - # Run response handler response = handler(request, *args, **kwargs) if isawaitable(response): response = await response diff --git a/tests/test_middleware.py b/tests/test_middleware.py index 5ff9e9b5..dc1365da 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -71,6 +71,25 @@ def test_middleware_override_request(): assert response.text == 'OK' +def test_middleware_override_scope(): + app = Sanic('test_middleware_override_scope') + + @app.middleware + async def validate_request(request): + if not request.headers.get('X-REQUIRED-HEADER'): + return text('X-REQUIRED-HEADER is missing.', status=412) + + @app.route('/') + async def handler(request): + return text('OK') + + response = sanic_endpoint_test(app, uri='/', gather_request=False) + assert response.status == 412 + + response = sanic_endpoint_test(app, uri='/nothing/', gather_request=False) + assert response.status == 404 + + def test_middleware_override_response(): app = Sanic('test_middleware_override_response')