about summary refs log tree commit diff
path: root/gn_auth/errors/__init__.py
diff options
context:
space:
mode:
Diffstat (limited to 'gn_auth/errors/__init__.py')
-rw-r--r--gn_auth/errors/__init__.py48
1 files changed, 48 insertions, 0 deletions
diff --git a/gn_auth/errors/__init__.py b/gn_auth/errors/__init__.py
new file mode 100644
index 0000000..97d1e9e
--- /dev/null
+++ b/gn_auth/errors/__init__.py
@@ -0,0 +1,48 @@
+"""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)