aboutsummaryrefslogtreecommitdiff
path: root/qc_app/errors.py
blob: bcd354312018db95f40a40445feb5dfc0d77e476 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""Application error handling."""
import traceback
from werkzeug.exceptions import HTTPException

import MySQLdb as mdb
from flask import Flask, request, render_template, current_app as app

def handle_general_exception(exc: Exception):
    """Handle generic exceptions."""
    trace = traceback.format_exc()
    app.logger.error(
        "Error (%s.%s): Generic unhandled exception!! (URI: %s)\n%s",
        exc.__class__.__module__, exc.__class__.__name__, request.url, trace)
    return render_template("unhandled_exception.html", trace=trace)

def handle_http_exception(exc: HTTPException):
    """Handle HTTP exceptions."""
    app.logger.error(
        "HTTP Error %s: %s", exc.code, exc.description, exc_info=True)
    return render_template(f"http-error.html",
                           request_url=request.url,
                           exc=exc,
                           trace=traceback.format_exception(exc)), exc.code

def register_error_handlers(appl: Flask):
    """Register top-level error/exception handlers."""
    appl.register_error_handler(Exception, handle_general_exception)
    appl.register_error_handler(HTTPException, handle_http_exception)
    appl.register_error_handler(mdb.MySQLError, handle_general_exception)