about summary refs log tree commit diff
path: root/gn_auth/errors/common.py
diff options
context:
space:
mode:
authorFrederick Muriuki Muriithi2025-07-09 11:51:37 -0500
committerFrederick Muriuki Muriithi2025-07-09 11:57:25 -0500
commit1740ccbe30946aa6693a6a9ed8211a2ff7cfbf3d (patch)
treeaf5b89ba28a39cd859ae943e8882f39f5ae54069 /gn_auth/errors/common.py
parente7a89061cba689268daf4991038d9bec763a06d3 (diff)
downloadgn-auth-1740ccbe30946aa6693a6a9ed8211a2ff7cfbf3d.tar.gz
Improve error handling and reporting.
- Refactor out common functionality into reusable utilities
- Handle errors from the Authlib library/package
- Handle 4xx errors generically.
Diffstat (limited to 'gn_auth/errors/common.py')
-rw-r--r--gn_auth/errors/common.py41
1 files changed, 41 insertions, 0 deletions
diff --git a/gn_auth/errors/common.py b/gn_auth/errors/common.py
new file mode 100644
index 0000000..7ef18cf
--- /dev/null
+++ b/gn_auth/errors/common.py
@@ -0,0 +1,41 @@
+"""Common utilities."""
+import logging
+import traceback
+
+from flask import request, jsonify, render_template
+
+logger = logging.getLogger(__name__)
+
+
+def add_trace(exc: Exception, errobj: dict) -> dict:
+    """Add the traceback to the error handling object."""
+    return {
+        **errobj,
+        "error-trace": "".join(traceback.format_exception(exc))
+    }
+
+
+def build_handler(description: str):
+    """Generic utility to build error handlers."""
+    def __handler__(exc: Exception):
+        error = (exc.name if hasattr(exc, "name") else exc.__class__.__name__)
+        status_code = exc.code if hasattr(exc, "code") else 500
+        content_type = request.content_type
+        if bool(content_type) and content_type.lower() == "application/json":
+            return (
+                jsonify(add_trace(exc,
+                                  {
+                                      "requested-uri": request.url,
+                                      "error": error,
+                                      "error_description": description
+                                  })),
+                status_code)
+
+        return (render_template(f"http-error-{str(status_code)[0:-2]}xx.html",
+                                error=exc,
+                                page=request.url,
+                                description=description,
+                                trace=traceback.format_exception(exc)),
+                status_code)
+
+    return __handler__