From 69e7f9bc5ed70c7e117c85452c92ba1eb05ae738 Mon Sep 17 00:00:00 2001 From: Lubomír Sedlář Date: Dec 03 2020 12:09:23 +0000 Subject: Handle NotFound raised by the framework There are two different NotFound exception: one specific to the application, and one raised by the framework when trying to access url which does not have a handler. The first one is working well, the second wasn't handled and instead was actually being set as 500 (even though the response body talked about 404). --- diff --git a/cts/__init__.py b/cts/__init__.py index c255a6a..345a737 100644 --- a/cts/__init__.py +++ b/cts/__init__.py @@ -26,7 +26,7 @@ from logging import getLogger from flask import Flask, jsonify from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy -from werkzeug.exceptions import BadRequest, Unauthorized +from werkzeug.exceptions import BadRequest, Unauthorized, NotFound as WerkzeugNotFound from cts.logger import init_logging from cts.config import init_config @@ -69,9 +69,14 @@ def json_error(status, error, message): @app.errorhandler(NotFound) +@app.errorhandler(WerkzeugNotFound) def notfound_error(e): """Flask error handler for NotFound exceptions""" - return json_error(404, 'Not Found', e.args[0]) + try: + msg = e.args[0] + except IndexError: + msg = "The requested URL was not found on the server." + return json_error(404, 'Not Found', msg) @app.errorhandler(Unauthorized)