"""Handle application level errors.""" import logging import traceback from werkzeug.exceptions import NotFound, HTTPException from flask import (Flask, request, jsonify, render_template) from gn_auth.auth.errors import AuthorisationError from .http import http_error_handlers from .authlib import authlib_error_handlers from .common import add_trace, build_handler logger = logging.getLogger(__name__) __all__ = ["register_error_handlers"] def handle_general_exception(exc: Exception): """Handle generic unhandled exceptions.""" exc_args = [str(x) for x in exc.args] _handle = build_handler("A generic exception occurred: " " ".join(exc_args)) return _handle(exc) def handle_authorisation_error(exc: AuthorisationError): """Handle AuthorisationError if not handled anywhere else.""" exc_args = [str(x) for x in exc.args] _handle = build_handler("A generic authorisation error occurred: " " ".join(exc_args)) return _handle(exc) def register_error_handlers(app: Flask): """Register ALL defined error handlers""" _handlers = { **authlib_error_handlers(), **http_error_handlers(), Exception: handle_general_exception, AuthorisationError: handle_authorisation_error } for class_, error_handler in _handlers.items(): logger.debug("Register handler for %s", class_.__name__) app.register_error_handler(class_, error_handler)