From ac11c943c50633ed39f31688e78f9bcb933f78a7 Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Tue, 26 Sep 2023 03:14:39 +0300 Subject: Handle AuthorisationError at the top-level Add an error handler to gracefully handle the custom AuthorisationError at the application's top-level to avoid having to manually handle it everywhere that the error (and its sub-classes) might be raised. --- gn_auth/__init__.py | 3 +++ gn_auth/errors.py | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 gn_auth/errors.py (limited to 'gn_auth') diff --git a/gn_auth/__init__.py b/gn_auth/__init__.py index 446ba19..6df1bc7 100644 --- a/gn_auth/__init__.py +++ b/gn_auth/__init__.py @@ -12,6 +12,7 @@ from gn_auth.auth.views import oauth2 from gn_auth.auth.authentication.oauth2.server import setup_oauth2_server from . import settings +from .errors import register_error_handlers class ConfigurationError(Exception): """Raised in case of a configuration error.""" @@ -74,4 +75,6 @@ def create_app(config: Optional[dict] = None) -> Flask: app.register_blueprint(misc, url_prefix="/") app.register_blueprint(oauth2, url_prefix="/auth") + register_error_handlers(app) + return app diff --git a/gn_auth/errors.py b/gn_auth/errors.py new file mode 100644 index 0000000..bd2c5eb --- /dev/null +++ b/gn_auth/errors.py @@ -0,0 +1,20 @@ +"""Handle application level errors.""" +from flask import Flask, jsonify, current_app + +from gn_auth.auth.authorisation.errors import AuthorisationError + +def handle_authorisation_error(exc: AuthorisationError): + """Handle AuthorisationError if not handled anywhere else.""" + current_app.logger.error(exc) + return jsonify({ + "error": type(exc).__name__, + "error_description": " :: ".join(exc.args) + }), exc.error_code + +__error_handlers__ = { + AuthorisationError: handle_authorisation_error +} +def register_error_handlers(app: Flask): + """Register ALL defined error handlers""" + for klass, error_handler in __error_handlers__.items(): + app.register_error_handler(klass, error_handler) -- cgit v1.2.3