From e81f30208433ef7d3691119293e6978cadc866a3 Mon Sep 17 00:00:00 2001 From: Leo Hemsted Date: Fri, 22 Jun 2018 17:36:58 +0100 Subject: [PATCH] handle 405 METHOD NOT ALLOWEDs (show the "something went wrong" error page). also catch any other werkzeug http exceptions and show an appropriate template, if it exists --- app/__init__.py | 21 ++++++++++++++++----- tests/app/main/test_errorhandlers.py | 8 ++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 3f2d11606..ee6a4a899 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -34,9 +34,8 @@ from notifications_utils.recipients import ( ) from notifications_utils.formatters import formatted_list from notifications_utils.sanitise_text import SanitiseASCII -from werkzeug.exceptions import abort +from werkzeug.exceptions import abort, HTTPException as WerkzeugHTTPException from werkzeug.local import LocalProxy -from werkzeug.routing import RequestRedirect from app import proxy_fix from app.config import configs @@ -584,9 +583,21 @@ def register_errorhandlers(application): # noqa (C901 too complex) ), 400) return useful_headers_after_request(resp) - @application.errorhandler(RequestRedirect) - def handle_301(error): - return error + @application.errorhandler(405) + def handle_405(error): + resp = make_response(render_template( + "error/400.html", + message=['Something went wrong, please go back and try again.'] + ), 405) + return useful_headers_after_request(resp) + + @application.errorhandler(WerkzeugHTTPException) + def handle_http_error(error): + if error.code == 301: + # RequestRedirect exception + return error + + return _error_response(error.code) @application.errorhandler(500) @application.errorhandler(Exception) diff --git a/tests/app/main/test_errorhandlers.py b/tests/app/main/test_errorhandlers.py index 770efbbdf..1b36bcbbc 100644 --- a/tests/app/main/test_errorhandlers.py +++ b/tests/app/main/test_errorhandlers.py @@ -60,3 +60,11 @@ def test_csrf_redirects_to_sign_in_page_if_not_signed_in(client, mocker): assert response.status_code == 302 assert response.location == url_for('main.sign_in', next='/cookies', _external=True) + + +def test_405_returns_something_went_wrong_page(client, mocker): + response = client.post('/') + + assert response.status_code == 405 + page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser') + assert page.h1.string.strip() == 'Something went wrong, please go back and try again.'