From 1c681c95bef461de7eb5916f93232879196ad08a Mon Sep 17 00:00:00 2001 From: Matt Fisher Date: Sun, 3 Sep 2023 13:16:28 -0600 Subject: [PATCH] Handle errors TODO: TESTING config setting isn't applying as expected --- docker-compose.dev.yml | 4 ++-- usaon_vta_survey/__init__.py | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 13d13d1c..d4da7e23 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -21,10 +21,10 @@ services: - "USAON_VTA_LOGIN_DISABLED=true" # Use a local file DB instead of a remote one: - "USAON_VTA_DB_SQLITE=true" + # Disable error handlers and allow exceptions to propagate: + - "USAON_VTA_TESTING=True" # Enable the in-browser debugger: - "FLASK_DEBUG=True" - # Disable error handlers and allow exceptions to propagate: - - "FLASK_TESTING=True" # Development DANGER ZONE: Do not use the below settings except for diff --git a/usaon_vta_survey/__init__.py b/usaon_vta_survey/__init__.py index 78705409..133f0a42 100644 --- a/usaon_vta_survey/__init__.py +++ b/usaon_vta_survey/__init__.py @@ -1,7 +1,7 @@ import os from typing import Final -from flask import Flask +from flask import Flask, render_template from flask_bootstrap import Bootstrap5 from flask_sqlalchemy import SQLAlchemy from sqlalchemy import MetaData @@ -28,6 +28,8 @@ app = Flask(__name__) app.config['SECRET_KEY'] = os.environ.get('FLASK_SECRET_KEY', 'youcanneverguess') app.config['LOGIN_DISABLED'] = envvar_is_true("USAON_VTA_LOGIN_DISABLED") +# TODO: This should disable error handlers but it doesn't: +app.config['TESTING'] = envvar_is_true("USAON_VTA_TESTING") app.config['SQLALCHEMY_DATABASE_URI'] = db_connstr(app) db.init_app(app) @@ -35,6 +37,19 @@ app.jinja_env.globals.update(sqla_inspect=sqla_inspect, __version__=__version__) + +@app.errorhandler(Exception) +def handle_exception(e): + """Naively handle all exceptions the same way. + + TODO: Not all exceptions should necessarily be handled the same way. Think harder. + Read docs: https://flask.palletsprojects.com/en/2.3.x/errorhandling/ + TODO: Some way to link error messages users see with full tracebacks in logs. A + random request ID? + """ + return render_template("error.html", message=e) + + # NOTE: This is a circular import, but it's specified by the Flask docs: # https://flask.palletsprojects.com/en/3.1.x/patterns/packages/ import usaon_vta_survey.routes # noqa: E402, F401