From 0bc0bd0673f8c167558b62645cbba652f329ab08 Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Mon, 29 Jan 2024 06:48:06 +0300 Subject: Create framework for error handling and handle connection errors --- gn2/wqflask/app_errors.py | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) (limited to 'gn2/wqflask/app_errors.py') diff --git a/gn2/wqflask/app_errors.py b/gn2/wqflask/app_errors.py index c6081e08..b0e3b665 100644 --- a/gn2/wqflask/app_errors.py +++ b/gn2/wqflask/app_errors.py @@ -1,9 +1,42 @@ """Handle errors at the application's top-level""" -from flask import flash, redirect, current_app, render_template +import os +import random +import datetime +import traceback + +from werkzeug.exceptions import InternalServerError from authlib.integrations.base_client.errors import InvalidTokenError +from flask import ( + flash, request, redirect, current_app, render_template, make_response) from gn2.wqflask.oauth2 import session from gn2.wqflask.decorators import AuthorisationError +from gn2.wqflask.external_errors import ExternalRequestError + +def render_error(exc): + """Render the errors consistently.""" + error_desc = str(exc) + time_str = datetime.datetime.utcnow().strftime('%l:%M%p UTC %b %d, %Y') + formatted_lines = f"{request.url} ({time_str}) \n{traceback.format_exc()}" + + current_app.logger.error("(error-id: %s): %s\n\n%s", + exc.errorid if hasattr(exc, "errorid") else uuid4(), + error_desc, + formatted_lines) + + animation = request.cookies.get(error_desc[:32]) + if not animation: + animation = random.choice([fn for fn in os.listdir( + "./gn2/wqflask/static/gif/error") if fn.endswith(".gif")]) + + resp = make_response(render_template( + "error.html", + message=error_desc, + stack={formatted_lines}, + error_image=animation, + version=current_app.config.get("GN_VERSION"))) + resp.set_cookie(error_desc[:32], animation) + return resp def handle_authorisation_error(exc: AuthorisationError): """Handle AuthorisationError if not handled anywhere else.""" @@ -20,6 +53,8 @@ def handle_invalid_token_error(exc: InvalidTokenError): __handlers__ = { AuthorisationError: handle_authorisation_error, + ExternalRequestError: lambda exc: render_error(exc), + InternalServerError: lambda exc: render_error(exc), InvalidTokenError: handle_invalid_token_error } -- cgit v1.2.3