From a495be9b720a8f865744c4b6bf591837de72089c Mon Sep 17 00:00:00 2001 From: Ryan Shaw Date: Tue, 26 Sep 2023 12:47:11 -0400 Subject: [PATCH] add custom 404 handler --- periodo/__init__.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/periodo/__init__.py b/periodo/__init__.py index a663994..e0ca65a 100644 --- a/periodo/__init__.py +++ b/periodo/__init__.py @@ -4,8 +4,9 @@ import logging from uuid import UUID from logging.config import dictConfig -from flask import Flask, make_response, g from flask_principal import Principal, identity_loaded +from flask import Flask, make_response, g, request +from werkzeug.exceptions import NotFound from werkzeug.http import http_date from werkzeug.middleware.proxy_fix import ProxyFix from werkzeug.routing import BaseConverter @@ -149,6 +150,24 @@ def add_server_version_header(response): import periodo.auth # noqa: E402 import periodo.database # noqa: E402 +import periodo.highlight # noqa: E402 + + +@app.errorhandler(NotFound) +def handle_not_found_error(_): + message = { + "code": 404, + "status": "Not Found", + "message": f"{request.path[1:]} is not a valid PeriodO identifier. Perhaps you followed a broken link?", + } + if request.accept_mimetypes.best == "application/json": + return make_response( + json.dumps(message), + 404, + {"Content-Type": "application/json"}, + ) + else: + return make_response(periodo.highlight.as_json(message), 404) @app.errorhandler(periodo.auth.AuthenticationFailed)