diff options
author | Frederick Muriuki Muriithi | 2025-07-09 09:36:21 -0500 |
---|---|---|
committer | Frederick Muriuki Muriithi | 2025-07-09 09:36:21 -0500 |
commit | 72fcbb0fc1e0c347c827042722c68ab5efbcfb2e (patch) | |
tree | be8752f36cda38c628d87f38e693e0d6e7824660 /gn_auth/errors/__init__.py | |
parent | f703399bdda4d4f4362653bdea4190804c3590d5 (diff) | |
download | gn-auth-72fcbb0fc1e0c347c827042722c68ab5efbcfb2e.tar.gz |
Move error handling into separate package.
Diffstat (limited to 'gn_auth/errors/__init__.py')
-rw-r--r-- | gn_auth/errors/__init__.py | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/gn_auth/errors/__init__.py b/gn_auth/errors/__init__.py new file mode 100644 index 0000000..533a842 --- /dev/null +++ b/gn_auth/errors/__init__.py @@ -0,0 +1,62 @@ +"""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 .tracing import add_trace +from .http import http_error_handlers + +logger = logging.getLogger(__name__) + +__all__ = ["register_error_handlers"] + + +def handle_general_exception(exc: Exception): + """Handle generic unhandled exceptions.""" + logger.error("Error occurred!", exc_info=True) + content_type = request.content_type + if bool(content_type) and content_type.lower() == "application/json": + exc_args = [str(x) for x in exc.args] + msg = ("The following exception was raised while attempting to access " + f"{request.url}: {' '.join(exc_args)}") + return jsonify(add_trace(exc, { + "error": type(exc).__name__, + "error_description": msg + })), 500 + + return render_template("50x.html", + page=request.url, + error=exc, + trace=traceback.format_exception(exc)), 500 + + +def handle_authorisation_error(exc: AuthorisationError): + """Handle AuthorisationError if not handled anywhere else.""" + logger.error("Error occurred!", exc_info=True) + logger.error(exc) + return jsonify(add_trace(exc, { + "error": type(exc).__name__, + "error_description": " :: ".join(exc.args) + })), exc.error_code + +__error_handlers__ = { + Exception: handle_general_exception, + AuthorisationError: handle_authorisation_error +} + + +def register_error_handlers(app: Flask): + """Register ALL defined error handlers""" + _handlers = { + **__error_handlers__, + **http_error_handlers() + } + for class_, error_handler in __error_handlers__.items(): + app.register_error_handler(class_, error_handler) |