Catch database connection error and show error page

Closes: #5
This commit is contained in:
Edward Betts 2023-11-17 12:21:07 -03:00
parent 3b81bc0d96
commit d425133423
2 changed files with 26 additions and 0 deletions

View file

@ -3,6 +3,7 @@
import random import random
import typing import typing
import sqlalchemy.exc
from flask import Flask, jsonify, redirect, render_template, request, url_for from flask import Flask, jsonify, redirect, render_template, request, url_for
from sqlalchemy.orm.query import Query from sqlalchemy.orm.query import Query
from werkzeug.wrappers import Response from werkzeug.wrappers import Response
@ -168,9 +169,16 @@ def redirect_to_detail(q: str) -> Response:
return redirect(url_for("detail_page", lat=lat, lon=lon)) return redirect(url_for("detail_page", lat=lat, lon=lon))
@app.errorhandler(sqlalchemy.exc.OperationalError)
def handle_database_error(error: Exception) -> tuple[str, int]:
"""Show error screen on database error."""
return render_template("database_error.html"), 500
@app.route("/") @app.route("/")
def index() -> str | Response: def index() -> str | Response:
"""Index page.""" """Index page."""
database.session.execute("SELECT 1")
q = request.args.get("q") q = request.args.get("q")
if q and q.strip(): if q and q.strip():
return redirect_to_detail(q) return redirect_to_detail(q)
@ -242,6 +250,7 @@ def build_detail_page(lat: float, lon: float) -> str:
@app.route("/detail") @app.route("/detail")
def detail_page() -> Response | str: def detail_page() -> Response | str:
"""Detail page.""" """Detail page."""
database.session.execute("SELECT 1")
try: try:
lat_str, lon_str = request.args["lat"], request.args["lon"] lat_str, lon_str = request.args["lat"], request.args["lon"]
lat, lon = float(lat_str), float(lon_str) lat, lon = float(lat_str), float(lon_str)

View file

@ -0,0 +1,17 @@
{% extends "base.html" %}
{% block title %}Geocode to Commons: database error{% endblock %}
{% block content %}
<div class="m-3">
<h1>Geocode coordinates to Commons Category</h1>
<div class="alert alert-danger" role="alert">
Error: database connection not available.
</div>
</div>
{% endblock %}